我尝试将我的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成为单身人士?
答案 0 :(得分:1)
在+sharedAppDelegate
中,您正在分配AppDelegate
类的新实例。相反,您想要的是在应用程序启动时捕获UIApplication
为您创建的实例。最简单的方法是使用sharedApplication
单例,它已经存储了委托实例:
+ (AppDelegate *)sharedAppDelegate {
return [[UIApplication shareApplication] delegate];
}