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]
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With