dev gr dev gr - 1 year ago 79
iOS Question

Possibilities of Singleton instance getting deallocated automatically

I am creating singleton instance as below:

+(MySingleton*)sharedInstance {
static MySingleton sharedObject = nil;

static dispatch_once_t predicate = 0;

dispatch_once(&predicate, ^{
sharedObject = [[MySingleton alloc] init];
return sharedObject;

What are the possibilities of
getting deallocated automatically?

How can I be sure that
will remain in memory until app is terminated?

Answer Source

As another answer rightly points out, this shared singleton will never be deallocated. There are two parts to answer "why", both of which come from the following line:

static MySingleton * sharedObject = nil;

First, static. static, when used inside of a function like this, modifies the lifetime of a variable, changing it from automatic, the implicit default, to static. This means that this variable exists for the entire lifetime of the program.

Second, this declaration makes sharedObject a strong reference. Variables in Objective-C are strong by default, but to be pedantic, you could have written:

static __strong MySingleton * sharedObject = nil;

So: we have a variable that lives for the entire duration of your program (static), and that maintains a strong reference to the object it represents (__strong). With these two pieces of information, plus the fact that you never change the object to which the variable points, you can deduce that sharedObject will never be deallocated.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download