views:

114

answers:

2

This question is similar to this other post, but I'm new to iPhone development and I'm getting used to the good practices for organizing my data throughout my app. I understand the ApplicationDelegate object to be the best place to manage data that is global to my app, correct? If so, how can I access data that's stored in my App Delegate from various view controllers? For example, my array is created in the app delegate as such...

appdelegate.m

sectionTitles = [[NSArray alloc] initWithObjects: @"Title1", @"Title2", @"Title3", nil];
rootViewController.appDelegate = self;

and I need to access it throughout the different views of my app, like my root table view controller...

rootviewcontroller.m

NSUInteger numTableSections = [self.appDelegate.sectionTitles count];

Is this the best way to do it or are there any reasons I should organize my data a better way? I ask because I can never really get too comfortable with using global variables (I blame my college professors), though I'm not sure if this can be considered a global variable.

Thanks so much in advance for your help!

+1  A: 

This should work:

self.appDelegate = ( YourApplicationDelegate *) [[UIApplication sharedApplication] delegate];
Jacob Relkin
thanks, that'll free me from keeping track of references to my app delegate in each view. good tip!
BeachRunnerJoe
+1  A: 

I understand the ApplicationDelegate object to be the best place to manage data that is global to my app, correct?

Not really (your college professors had a point). It's tempting to start putting a lot of stuff into the app delegate, but it's not a very sustainable practice. See my answer here.

And read this good post by Matt Gallagher for more depth.

That said, I often put something like this in my app delegate header:

#define APP_DELEGATE (MyAppDelegate*) [[UIApplication sharedApplication] delegate]

so I can easily do things like:

int n = [[APP_DELEGATE sectionTitles]count];
Felixyz
I logged in specifically so I could up vote this. I really think the app delegate is a bad place for global dats. I tend to use singletons for things like that.
Alex
thanks, felix, great post!
BeachRunnerJoe