0

I'm trying to make an app (using storyboard) and I want to populate it with events. In my MapViewController.h I have:

#imports

extern NSMutableArray* events;

@interface MapViewController : etc, etc{
..
}

So what I want is to be able to import this .h file in, for example, my AppDelegate.m file and in there in appDidFinishLoading do stuff like:

Event *event =  [[Event alloc] init];
event.blabla = blabla;
...
[events addObject:event];

and at the same time in my MapViewController.m I want a function that adds these events to my MKMapView (which is defined in my mapviewcontroller and called worldView)

so:

@implementation MapViewController.m

-(void)setEvents{
    for(int i = 0; i<[events count]; i++)
        [worldView addAnnotation:[events objectAtIndex:i]];
}

...

As you might have guessed, it's failing during the linking part of the build with the following errors:

Undefined symbols for architecture armv7:
"_events", referenced from:
-[AppDelegate applicationdidFini... ]
-[MapViewController setEVents] in ...
..
clang: error: linker command failed with exit code 1 (use -v to see invocation)

So.. Yeah.. Please help ^^

Spyral
  • 760
  • 1
  • 12
  • 33

2 Answers2

0

Never ever use global variables fur such a purpose, they are evil.

Better use a singleton (that is a so called design pattern) based approach creating something like a "manager" (e.g. EventManager class) to share data between independent controllers.

yan.kun
  • 6,820
  • 2
  • 29
  • 38
  • Could you elaborate it a bit more how I would use that here? – Spyral Jul 16 '12 at 09:37
  • First you should read about singleton: http://en.wikipedia.org/wiki/Singleton_pattern and then how to implement it in Objective-C: http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like – yan.kun Jul 16 '12 at 09:56
0

There are better patterns such as the singleton pattern mentioned by yan.kun but the way you would do what you are trying to do is to put this line in AppDelegate.m outside of your @implementation:

NSMutableArray* events;

This provides a global space for it so you won't get the linker error. Then you need to init the events array before any of the various classes that use it need it. Solving this initialization problem robustly is one of the reasons that other patterns are much better. In your case you can probably get away with doing this early in your AppDelegate did finish launching method.

P.S. If you must use global variables don't name them so generically as "events" as the chance of name collision is very high.

torrey.lyons
  • 5,519
  • 1
  • 23
  • 30