作为单身的iOS AppDelegate未能返回同一个实例

时间:2015-07-09 07:12:26

标签: ios objective-c singleton appdelegate

我尝试将我的AppDelegate作为单身人士,并通过我的应用程序访问它,如:

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]);
}

登录控制台:

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

为什么推出的那个与共享的一个不一样?

我是不是真的让AppDelegate成为单身人士?

1 个答案:

答案 0 :(得分:1)

+sharedAppDelegate中,您正在分配AppDelegate类的新实例。相反,您想要的是在应用程序启动时捕获UIApplication为您创建的实例。最简单的方法是使用sharedApplication单例,它已经存储了委托实例:

+ (AppDelegate *)sharedAppDelegate {
    return [[UIApplication shareApplication] delegate];
}