Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use a property for the app delegate?

I'm auditing some code that has an appDelegate property in many of the view controllers.

@property (nonatomic, unsafe_unretained) TheAppDelegate *appDelegate;

Leaving aside the design implications of such coupling, is there any benefit, other than convenience, of an appDelegate property versus retrieving the app delegate:

TheAppDelegate *appDelegate = (TheAppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate someMethod];
like image 641
Jason McCreary Avatar asked Feb 16 '23 17:02

Jason McCreary


2 Answers

I also sometimes do this, ie. declare a property for a dependency that can be fetched using a singleton access method:

@class Foo : NSObject
@property(strong) NSNotificationCenter *notificationCenter;
@end

@implementation Foo

- (id) init
{
    self = [super init];
    [self setNotificationCenter:[NSNotificationCenter defaultCenter]];
    return self;
}

@end

The advantage is that you get looser coupling on the dependency. You can easily supply your own mocked instance, for example. In some cases it also makes the code shorter, writing _notificationCenter instead of [NSNotificationCenter defaultCenter].

And a third reason that I can think of is that declaring the property makes the dependency explicit: you know by looking at the public API that the state or behaviour of the object depends on the app delegate. Using a singleton in the class implementation completely hides this fact.

But if there are many controllers in your app that depend on the app delegate, it’s probably just a design deficiency.

like image 55
zoul Avatar answered Mar 05 '23 02:03

zoul


To answer the question as framed.

The specific benefits are :-

Cleaner code - The property is set once ( and could be read only). If you use it more than once

self.appDelegate is simpler than fetching the appDelegate from the shared application every time. ( and simpler is better)

There might be a minor efficiency advantage ( although this is definitely premature optimisation and might not exist depending on the compiler).

I have to agree with CodaFi that it is a bit smelly, so there is the middle ground of creating some syntactic sugar to hide some complexity.

@class MyAppDelegate;
@interface MySharedAppDelegate : NSObject 

+ (MyAppDelegate*) appDelegate;
@end

#include "MyAppDelegate.h"
@implementation MySharedAppDelegate

+ ( MyAppDelegate*) appDelegate {
    return (MyAppDelegate*)[UIApplication sharedApplication].appDelegate;
}
@end
like image 36
Gordon Dove Avatar answered Mar 05 '23 02:03

Gordon Dove