Question

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?

Was it helpful?

Solution

In ARC defenition myclass *_instance; mean strong reference at myclass objects. So every assignment to _instance will retain object. And there is litle correction of yours code:

static myclass *_instance = nil;

+ (myclass *)sharedInstance {
    static dispatch_once_t _onceToken = 0;
    dispatch_once(&_onceToken, ^{
       _instance = [[myclass alloc] init];
       });
    return _instance;
}

OTHER TIPS

I think it should be:

static myclass *_instance = nil;

and because it is a global it is not released (until program termination).

You should change

myclass *_instance = nil;

to

static myclass *_instance = nil;

and

myclass = [[myclass alloc] init];

to

_instance = [[myclass alloc] init];

Hope this help.

Useful related stackoverflow question here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top