aneuryzm
aneuryzm

Reputation: 64834

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"]];
    [categories setObject:categImage forKey:categKey];
}

Update:

viewController init method

FlickrAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;

categories = appDelegate.categories;
categKeys = appDelegate.categoriesKeys;

Upvotes: 0

Views: 148

Answers (2)

FreeAsInBeer
FreeAsInBeer

Reputation: 12979

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.

Upvotes: 1

Rahul Vyas
Rahul Vyas

Reputation: 28720

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"];

Upvotes: 0

Related Questions