Single-instance mode for iOS development
In iOS development, there are many places where you can choose to use singleton mode. There are many times when you have to create an object, and you cannot create more than one, in order to prevent multiple objects from being created. The singleton pattern means that there is only one instance of a class. The singleton pattern ensures that a class has only one instance, and instantiates itself and provides this instance to the system as a whole.
One, the three main points of the Singleton model:
1. There is only one instance of the class;
2. The class must be able to create this instance on its own;
3. The class must be able to provide this instance to the entire system on its own.
Two, the advantages and disadvantages of the singleton model:
1. Memory consumption and running time
In contrast to the example of using singleton and non-singleton patterns, there are the following gaps in memory footprint and run time:
(1) Singleton mode: The singleton mode is judged each time it gets an instance, to see if the instance exists--if it exists, to return it, or to create an instance. Therefore, some time of judgment will be wasted. However, if no one has ever used this instance, it will not create an instance, saving memory space.
(2) Non-singleton mode: When the class loads, an instance of the class is created, regardless of whether you use it or not. Then, when each invocation, it is not necessary to determine whether the instance exists, saving the time to run. However, if the instance is not used, the memory is wasted.
2. Thread Security
(1) In terms of thread security, the non-synchronous singleton mode is unsafe. For example, there are two threads, one is thread A, the other is thread B, and if they call a method at the same time, it can cause concurrency problems. In this case, two instances are created, that is, the single-instance control is invalidated in the concurrency scenario.
(2) Non-singleton mode is thread-safe because the program is guaranteed to load only once, and no concurrency occurs when loading.
(3) Singleton mode if you want to implement thread safety, just add synchronized. But in this way, it will reduce the entire program access speed, and every time to judge, more trouble.
(4) Double check Lock: In order to solve (3) The tedious problem, you can use the "double check lock" way to achieve, so that can be both thread-safe, but also can make the program performance is not affected too much.
(4.1) Double check lock mechanism-not every time into the method to call need to synchronize, but first out of sync, and so into the method, first check whether the instance exists, if not exist before entering the following synchronization block, this is the first check. After entering the synchronization block, check again if the instance exists, and if it does not exist, create an instance in the case of synchronization, which is the second check. In this way, only one synchronization is required, which reduces the time wasted in the synchronization of multiple judgements.
(4.2) Double check and lock mechanism implementation, will use a keyword volatile. It means that the value of the variable modified by the volatile will not be cached by the local thread, and all reads and writes to the variable are directly manipulated to share the memory, thus ensuring that multiple threads can handle the variable correctly. This approach enables thread-safe creation of instances without much impact on performance. It is only in the first time to create the instance synchronization, the future does not need synchronization, thereby speeding up the speed of operation.
3. The singleton mode prevents other objects from instantiating copies of their own objects, ensuring that all objects have access to unique instances.
4. Because the singleton pattern class controls the instantiation process, the class can be more flexible in modifying the instantiation process.
Third, the singleton mode in iOS
1. Basic steps:
(1) To create a static instance for a singleton object, can be written as a global, can also be implemented in the class method, and initialized to nil;
(2) Implement an instance construction method to check if the static instance declared above is nil, and if so, create and return an instance of this class;
(3) Rewrite the Allocwithzone method to ensure that other people directly use Alloc and Init to try to acquire a new strength without creating a new instance;
(4) Proper realization of allocwithezone,copywithzone,release and autorelease.
1 Here is an example of how to create a singleton pattern in Imagestore:2 3 in the ImageStore.h file, write the following code:4 #import<Foundation/Foundation.h>5 @interfaceImagestore:nsobject6 {7Nsmutabledictionary *dictionary;8 }9+ (imagestore*) Defaultimagestore;Ten- (void) SetImage: (uiimage*) Image forkey: (nsstring*)string; One-(uiimage*) Imageforkey: (nsstring*)string; A- (void) Deleteimageforkey: (nsstring*)string; - @end - the in the imagestore.m file, write the following code: - #import "ImageStore.h" - StaticImagestore *defaultimagestore =Nil; - @implementationImagestore + //prevent another instance of this type from being created -+ (ID) Allocwithzone: (Nszone *) Zone + { A return[self defaultimagestore]; at } -+ (imagestore*) Defaultimagestore - { - if(!Defaultimagestore) - { - //Create a single case inDefaultimagestore =[[Super Allocwithzone:null]init]; - } to + returnDefaultimagestore; - } the- (ID) Init * { $ if(Defaultimagestore)Panax Notoginseng { - returnDefaultimagestore; the } + ASelf =[Super init]; the + if(self) - { $Dictionary =[[Nsmutabledictionary alloc]init]; $ } - - returnSelf ; the } -- (void) SetImage: (UIImage *) image forkey: (NSString *)stringWuyi { the[Dictionary setobject:image Forkey:string]; - } Wu-(uiimage*) Imageforkey: (NSString *)string - { About return[Dictionary Objectforkey:string]; $ } -- (void) Deleteimageforkey: (NSString *)string - { - if(!string) A { + return; the } - $[Dictionary Removeobjectforkey:string]; the } the @end
Single-instance mode for iOS development