When we write a non-ARC code in order to create a singleton class, it goes something like this:
myclass * myc_ins = nil;
@implementation myclass
+(myclass *) getInstance {
if(!myc_ins)
myc_ins = [[myclass alloc] init];
return myc_ins;
}
// ...
BUT, if same code is written in ARC, it releases the object and when getInstance is called after some time, it returns some dangling pointer as the memory being pointed to is freed. Also, I have seen this code for ARC apps:
myclass *_instance = nil;
+ (myclass *)sharedInstance {
static dispatch_once_t _onceToken = 0;
dispatch_once(&_onceToken, ^{
myclass = [[myclass alloc] init];
});
return _instance;
}
Although the code inside dispatch_once gets executed once, how does in this case the compiler know to retain the _instance
variable?