单身人士呼叫死锁

时间:2015-01-28 03:43:04

标签: objective-c singleton

当我初始化像这样的单身时,我发现它会导致死锁。

@interface A : NSObject
@property (readwrite, nonatomic, assign) BOOL flag;
@end

@implementation A

+(instancetype)sharedInstance
{
    static id instance = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        instance = self.new;
    });
    return instance;
}

-(instancetype)init
{
    self = [super init];
    if(self != nil)
    {
        [A sharedInstance].flag = YES;
    }
    return self;
}
@end

有没有办法打破它?

1 个答案:

答案 0 :(得分:2)

问题在于这一行:

[A sharedInstance].flag = YES;

将其更改为:

self.flag = YES; // or _flag = YES;

正如您所知,init尝试在单身人士仍在创建时访问单身人士。