1

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!

Community
  • 1
  • 1
BeachRunnerFred
  • 18,070
  • 35
  • 139
  • 238

2 Answers2

4

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];
Community
  • 1
  • 1
Felixyz
  • 19,053
  • 14
  • 65
  • 60
  • 1
    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 Jun 06 '10 at 15:44
1

This should work:

self.appDelegate = ( YourApplicationDelegate *) [[UIApplication sharedApplication] delegate];
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320