简体   繁体   中英

How can I access data that's stored in my App Delegate from my various view controllers?

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

这应该工作:

self.appDelegate = ( YourApplicationDelegate *) [[UIApplication sharedApplication] delegate];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM