1

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?

StuR
  • 12,042
  • 9
  • 45
  • 66
  • See [Global variables for class methods](http://stackoverflow.com/questions/8498754/global-variables-for-class-methods/8498798#8498798) for some ideas. – jscs Aug 05 '12 at 19:57

3 Answers3

3

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 the UIApplication class. Use of the word "shared" in the selector is a good hint, and the docs for UIApplication clearly state that it is a singleton:

sharedApplication

Returns the singleton application instance.

+ (UIApplication *)sharedApplication

This all means that you can rest assured that you are not instantiating n objects when you call it n times.

jscs
  • 63,694
  • 13
  • 151
  • 195
Chris Trahey
  • 18,202
  • 1
  • 42
  • 55
  • Ah, I see. I tend to use static objects rather than singletons having come from a PHP / Javascript background to Objective-C. I didn't even take a second glance at sharedApplication, for some reason, I assumed that I had to create a singleton object of the UIApplication. Anyway, thanks. I will read the docs. – StuR Aug 06 '12 at 11:31
1

you are getting a reference to the app delegate and casting it to your particular class, you are not instantiating the app delegate with this code, so there is no memory issue

wattson12
  • 11,176
  • 2
  • 32
  • 34
0

No, your app method doesn't create any objects, it just finds a global one and returns a pointer to its property.

Phillip Mills
  • 30,888
  • 4
  • 42
  • 57