当我初始化像这样的单身时,我发现它会导致死锁。
@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
有没有办法打破它?
答案 0 :(得分:2)
问题在于这一行:
[A sharedInstance].flag = YES;
将其更改为:
self.flag = YES; // or _flag = YES;
正如您所知,init
尝试在单身人士仍在创建时访问单身人士。