从不调用Singleton dealloc

时间:2015-06-16 10:34:38

标签: objective-c macos singleton

我的程序启动并存在,无需触发dealloc。

@interface Printer : NSObject
+ (instancetype)instance;
-(void)print;
@end

@implementation Printer

+ (instancetype)instance {
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}
-(void) print {
    printf(@"Printer printing...\n");
}
-(void)dealloc {
    printf(@"Printer dealloc\n");
}
@end

int main (int argc, const char * argv[])
{
    Printer* tmp = [Printer instance];
    [tmp print];
}

我得到以下输出:

Printer printing...
Program ended with exit code: 0

根据输出,永远不会调用dealloc。即使触发我的控制台应用程序,也不会触发dealloc内部的断点。

任何想法有什么不对? 我相信它归因于static sharedInstance变量,但不知道如何处理它。

0 个答案:

没有答案