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!
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];
This should work:
self.appDelegate = ( YourApplicationDelegate *) [[UIApplication sharedApplication] delegate];
精彩评论