iOS: Simple question about the app design and how to share a NSDictionary among viewControllers
I have a simple design question. This code is in my appDelegate. I use it to load all images in a NSDictionary categories. Successively I pass the dictionary to the init method of the main NavigationViewController. Successively I pass the dictionary through all viewControllers pushed by the NavigationViewController, because I'm using the same icons everywhere.
I was wondering if this is the correct approach, or am I just wasting memory. In other terms, should I pass the dictionary through viewControllers, or should I use a singleton.. or what ? The reason I'm currently adopting this approach is that I don't have any reference from viewControllers to the app delegate.
//load categories pictures
NSArray *categoriesKeys = [[NSArray alloc] initWithObjects:
@"comedy",
@"commercial",
@"education",
@"family",
@"media",
@"music",
@"performing",
@"sport",
nil];
categories = [[NSMutableDictionary alloc] init];
for (NSString *categKey in categoriesKeys) {
UIImage * categImage = [UIImage imageNamed:[[@"icons/" stringByAppendingString:categKey] stringByAppendingString:@".png"]];
[cat开发者_如何学编程egories setObject:categImage forKey:categKey];
}
Update:
viewController init method
FlickrAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
categories = appDelegate.categories;
categKeys = appDelegate.categoriesKeys;
I would probably create a Singleton. A lot of people like placing shared code in the AppDelegate, but then that file gets cluttered and it becomes unclear what is going on throughout the file. Having a Singleton dedicated to this logic separates the code and makes it easier to change.
put all the code in your appDelegate in a function and call that function in applicationDidFinishLaunching method . Access dictionary anywhere in the application like this
appNameDelegate* appDelegate = [UIApplication sharedApplication].delegate;
[appdelegate.categories objectForKey:@"WhatEver"];
精彩评论