单例调用死锁

Dead lock on Singleton call

我这样初始化单例的时候,发现会导致死锁

@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

有什么办法破解吗?

问题出在这一行:

[A sharedInstance].flag = YES;

改成这样:

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

如您所见,init 尝试在仍在创建单例时访问单例。