Use extern variable through different controllers

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 ^^

Answers


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.


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.


Need Your Help

back stack and statically added fragment

android android-fragments back-button back-stack fragmenttransaction

I have a fragment added statically from XML I want to replace this fragment by another fragment, I did that by adding this code:

Compiling C++ threads

c++ linux multithreading c++11

I'm trying to use threads on my C++ application.