I have a class which makes use of the app delegate, specifically it has an NSUserDefaults property which is being updated from my class.
In my auth class implementation file I’d have :
+ (BOOL) checkUserDefaults {
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if([appDelegate.session objectForKey:@"UserID"] != nil) {
return TRUE;
} else {
return FALSE;
}
}
+ (void) syncUserDefaults : (NSString *) UserID {
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
[appDelegate.session setObject:UserID forKey:@"UserID"];
[appDelegate.session synchronize];
}
How would I store this line of code:
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
As a global (to this class), so that I can just write for example [app.session setObject…]?
I could make a function:
+ (AppDelegate *) app
{
return (AppDelegate *) [[UIApplication sharedApplication] delegate];
}
And do [[self app].session setObject...], but say if I’m referencing the “app” function numerous times that would be instantiating the AppDelegate numerous times wouldn’t it?
This is exactly what the Singleton design pattern is for, and why the developers of the Cocoa framework use it where an object might be accessed across an app, but should only be instantiated once.
+[UIApplication sharedApplication]is a method which returns an existing instance of theUIApplicationclass. Use of the word “shared” in the selector is a good hint, and the docs forUIApplicationclearly state that it is a singleton:This all means that you can rest assured that you are not instantiating n objects when you call it n times.