简体   繁体   English

iOS AppDelegate作为单例无法返回相同实例

[英]iOS AppDelegate as singleton failed to return same instance

I tried to made my AppDelegate as a singleton and access it through my application like : 我试图将AppDelegate设置为单例,并通过以下应用程序访问它:

AppDelegate.h AppDelegate.h

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

+(AppDelegate*)sharedAppDelegate;

@end

AppDelegate.m 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 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? 我不是真的让AppDelegate单身吗?

In +sharedAppDelegate you're allocating a new instance of the AppDelegate class. +sharedAppDelegate您正在分配AppDelegate类的新实例。 What you want, instead, is to capture the instance created for you by UIApplication when the app is launched. 相反,您想要的是在启动应用程序时捕获UIApplication为您创建的实例。 The easiest way to do this is to use the sharedApplication singleton, which already stores the delegate instance: 最简单的方法是使用sharedApplication单例,该单例已经存储了委托实例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM