I\'ve been trudging through some code for two days trying to figure out why I couldn\'t fetch a global NSMutableArray variable I declared in the .h and implemented in .m and
If you have two view controllers that access the shared NSMutableDictionary, can you pass a pointer to the common dictionary into their respective init messages?
So in your AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// the app delegate doesn't keep a reference this, it just passes it to the
// view controllers who retain the data (and it goes away when both have been released)
NSMutableDictionary * commonData = [[NSMutableDictionary new] autorelease];
// some method to parse the JSON and build the dictionary
[self populateDataFromJSON:commonData];
// each view controller retains the pointer to NSMutableDictionary (and releases it on dealloc)
self.m_viewControllerOne = [[[UIViewControllerOne alloc] initWithData:commonData] autorelease];
self.m_viewControllerTwo = [[[UIViewControllerTwo alloc] initWithData:commonData] autorelease];
}
And in your respective UIViewControllerOne and UIViewControllerTwo implementations
- (id)initWithData:(NSMutableDictionary*)data
{
// call the base class ini
if (!(self=[super init]))
return nil;
// set your retained property
self.sharedData = data;
}
// don't forget to release the property
- (void)dealloc {
[sharedData release];
[super dealloc];
}
Just make a global variable. Global means outside any scope.
NSMutableDictionary *gDictionary;
@implementation ...
@end
There are global variables in Obj-C, you instantiate them in the App Delegate.
But onto your problem you probably want to pass the NSMutableDictonary when you instantiate the new view controller like [UIView alloc] initWithDictionary:(NSMutableDictionary *)dict; if you know what I mean.
In your example are you having a single class calling another class? I would think there is some kind of controller that determines which view controller to display and that would be the place to access and pass the dictionary
There are, in fact, a bunch of ways you can do this (without resorting to something extreme like writing to a file). You can create a "global" by using:
But all of these approaches make your view controller less modular (because they depend on reaching "outside" to find the global data), so the best approach is probably to make the dictionary a property of the view controller class that must be explicitly set by the caller (either within an initWithDictionary: method, or with a separate setter).