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?
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”.
Singleton Pattern can saves memory because object is not created at each request. Provide a global point of access to the object.
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.
In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With