Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS – AppDelegate as instance variable?

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]

like image 583
Peter Warbo Avatar asked Feb 10 '12 16:02

Peter Warbo


3 Answers

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.

like image 199
Lorenzo B Avatar answered Sep 27 '22 23:09

Lorenzo B


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.

like image 24
Lou Franco Avatar answered Sep 27 '22 23:09

Lou Franco


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.

like image 27
isaac Avatar answered Sep 28 '22 00:09

isaac