11

Is it okay to have the AppDelegate as an instance variable in a UIViewController? Like @property (nonatomic, weak) AppDelegate *appDelegate;

Why I'm asking is because I need to access it quite often so instead of doing:

AppDelegate *appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate]; 

[appDelegate doSomething]; 

I could do:

[appDelegate doSomething]

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
Peter Warbo
  • 11,136
  • 14
  • 98
  • 193

3 Answers3

19

Maybe it could be ok.

But my favourite solution is the following.

In your AppDelegate.h

+ (AppDelegate *)appDelegate;

In your AppDelegate.m

+ (AppDelegate *)appDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

Then use wherever you want:

AppDelegate* sharedDelegate = [AppDelegate appDelegate];

Some notes:

if you use AppDelegate for shared data you can read singletons-appdelegates-and-top-level.html.

if you use AppDelegate for your logical application workflow you can read handling-your-initial-view-controllers-for-iphone/

Hope it helps.

Alex Pretzlav
  • 15,505
  • 9
  • 57
  • 55
Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
  • `getAppDelegate` violates Apple's [naming guidelines](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-BCIGIJJF). A better name would be `+ (AppDelegate *)appDelegate;` or `+ (AppDelegate *)sharedAppDelegate;` – Alex Pretzlav Mar 01 '13 at 15:44
14

Or you could do

-(YourAppDelegate*) app
{
   return (YourAppDelegate*) [[UIApplication sharedApplication] delegate];
}

In a subclass of UIViewController -- then make that the base-class of all of your view controllers.

Then, [self app] works, and you don't have to keep a reference.

I do this to keep some common simple utilities there -- you also can do this with a category.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
4

The distinction between accessing the delegate by full expression versus with a (nonatomic, weak) property is arbitrary. Certainly, save yourself the lines of code by defining a property if you are going to call it frequently.

The question raises a larger issue of a possible encapsulation problem, however. Best practice suggests that calls go down the hierarchy versus up. Of course the app delegate is a bit of a special case, but still, my advice would be to consider possible ways of isolating whatever resource it is you need from the app delegate, and pass these references down your view controller hierarchy as that hierarchy is created.

isaac
  • 4,867
  • 1
  • 21
  • 31