Singleton instance capabilities automatically freed

I am creating a singleton instance as shown 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 options for automatically releasing sharedObject ?

How can I be sure that sharedObject will remain in memory until the application is completed?

+5
source share
4 answers

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

 static MySingleton * sharedObject = nil; 

The first is static . static , when used inside such a function, changes the lifetime of a variable, changing it from automatic , the implicit default value, to static . This means that this variable exists for the entire lifetime of the program.

Secondly, this declaration makes sharedObject a strong link. Variables in Objective-C are strong by default, but for pedantry you could write:

 static __strong MySingleton * sharedObject = nil; 

So: we have a variable that lives throughout your program ( static ), and which maintains a strong reference to the object that it represents ( __strong ). Using these two pieces of information, as well as the fact that you never change the object that the variable points to, you can conclude that sharedObject will never be freed.

+9
source

0 opportunity. It will never be released; static save it with a strong link. In the ARC world, you cannot just release something without saving it.

+3
source

I came across one very dubious case when it can be released and cause unfortunate problems, so for now there is something unusual to be careful.

If you pass your memory address to a third party low-level library, i.e. like user_data (or maybe you created a low-level c library), and this library frees up memory. You did not expect external libraries to release the user_data that you provide, but this was the case with the c cs sockets sockets library that I used.

+1
source

sharedObject will be released after the completion of the included functions and after the release of the contained blocks. so dispatch_once most likely frees the current block after running it once. this means that it will be released immediately after calling onece.

-6
source

Source: https://habr.com/ru/post/1208481/


All Articles