0

I tried to made my AppDelegate as a singleton and access it through my application like :

AppDelegate.h

/.../
@interface AppDelegate : UIResponder <UIApplicationDelegate>

+(AppDelegate*)sharedAppDelegate;

@end

AppDelegate.m

#import AppDelegate.h
/.../
@implementation AppDelegate

AppDelegate *sharedAppDelegate;

+ (AppDelegate *)sharedAppDelegate{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedAppDelegate = [[self alloc] init];
    });
      NSLog(@"shared app: %@",sharedAppDelegate)
      return sharedAppDelegate;

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSLog(@"launched app: %@",self);
}

MyClass.m

#import AppDelegate.h
/.../
- (void)viewDidLoad{
    [super viewDidLoad];
    NSLog(@"app in myClass: %@",[AppDelegate sharedAppDelegate]);
}

Logs in console:

[***]launched app:   <AppDelegate: 0x78757810>
[***]shared app:     <AppDelegate: 0x78f39760>
[***]app in myClass: <AppDelegate: 0x78f39760>

Why isn't the launched one the same as the shared one?

Am I not really make AppDelegate a singleton?

bluenowhere
  • 2,683
  • 5
  • 24
  • 37
  • 2
    AppDelegate is not singleton, its Application Responder class, which is always in memory, what you are trying to do is incorrect, you can't do self init with AppDelegate. Just use `(AppDelegate*)[[UIApplication shareApplication] delegate];` to get its actual memory reference. – iphonic Jul 09 '15 at 07:17
  • whoa thanks for the simple and clear comment ! guess I'll close this and read more docs ... – bluenowhere Jul 09 '15 at 07:23
  • @iphonic where does it come with " its Application Responder class, which is always in memory"? would you refer me to some source or guidance please? – bluenowhere Jul 09 '15 at 07:46

1 Answers1

1

In +sharedAppDelegate you're allocating a new instance of the AppDelegate class. What you want, instead, is to capture the instance created for you by UIApplication when the app is launched. The easiest way to do this is to use the sharedApplication singleton, which already stores the delegate instance:

+ (AppDelegate *)sharedAppDelegate {
    return [[UIApplication shareApplication] delegate];
}
Gianluca Tranchedone
  • 3,598
  • 1
  • 18
  • 33