Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 sharedObject getting deallocated automatically?

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

like image 410
dev gr Avatar asked Dec 06 '14 08:12

dev gr


People also ask

How should deallocate instance created by Singleton class?

And deletion of singleton class object would be allow only when the count is zero. To design C++ delete singleton instance, first, we need to make the singleton class destructor private, so, it can not be accessed from outside of the class. Hence, user cannot delete the singleton instance using the keyword “delete”.

Does Singleton save memory?

Singleton Pattern can saves memory because object is not created at each request. Provide a global point of access to the object.

How do you destroy a Singleton?

There is no way to destroy a Singleton without breaking the Singleton property. As others have said, maybe a Singleton isn't appropriate here. If the number of instances of the class can go down to zero, then it's not a Singleton.

What is the pattern that limits the number of instances of a class normally to 1?

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance.


2 Answers

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.

like image 50
ravron Avatar answered Nov 02 '22 13:11

ravron


0 possibility. It will never be released, static keeps it with strong reference. In ARC world you can't just release something without first retaining it.

like image 22
Rob Zombie Avatar answered Nov 02 '22 14:11

Rob Zombie