【发布时间】:2015-07-09 15:23:16
【问题描述】:
我尝试将我的 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 成为单例吗?
【问题讨论】:
-
AppDelegate 不是单例的,它的 Application Responder 类,它总是在内存中,你试图做的是不正确的,你不能用 AppDelegate 做自我初始化。只需使用
(AppDelegate*)[[UIApplication shareApplication] delegate];即可获取其实际内存引用。 -
哇,感谢您的简单明了的评论!我想我会关闭它并阅读更多文档...
-
@iphonic “它的应用程序响应程序类,它总是在内存中”?请给我一些资料或指导好吗?
标签: ios objective-c singleton appdelegate