Singleton mode for iOS development and iOS development

Source: Internet
Author: User

Singleton mode for iOS development and iOS development

Singleton mode for iOS development

In iOS development, the singleton mode is used in many places. In many cases, one object must be created and multiple objects cannot be created. To avoid creating multiple objects, use a single instance. The Singleton Mode means that a class has only one instance. The Singleton mode ensures that a class has only one instance, and the instance is self-instantiated and provided to the entire system.

I. Three Key Points of Singleton mode:

1. This class has only one instance;

2. This class must be able to create this instance by itself;

3. This class must be able to provide this instance to the entire system.

 

Ii. Advantages and Disadvantages of Singleton mode:

1. memory usage and running time

Compared with examples using Singleton mode and non-singleton mode, there is a gap between memory usage and running time:

(1) Singleton mode: The Singleton mode first determines whether the instance exists. If yes, the system returns the result. Otherwise, the system creates an instance. Therefore, some judgment time is wasted. However, if no one has ever used this instance, the instance will not be created, saving the memory space.

(2) Non-singleton mode: When a class is loaded, an instance of the class is created, whether or not you use it. Then, you do not need to determine whether the instance exists during each call, saving the running time. However, if the instance is not used, the memory will be wasted.

2. Thread Security

(1) In terms of thread security, the singleton mode without synchronization is insecure. For example, there are two threads, one is thread A and the other is thread B. If they call A method at the same time, it may cause concurrency problems. In this case, two instances are created, that is, the control of a single instance is invalid in the case of concurrency.

(2) The non-singleton mode is thread-safe, because the program is guaranteed to load only once and no concurrency occurs during loading.

(3) To implement thread security in singleton mode, you only need to add synchronized. However, this will reduce the access speed of the entire program, and it will be difficult to judge every time.

(4) double check locking: To solve (3) the tedious problem, you can use the "double check locking" method to achieve thread security, the program performance is not greatly affected.

(4.1) double check locking mechanism-not every time the method to be called needs to be synchronized, but not synchronized. After the method is entered, check whether the instance exists first, if it does not exist, enter the following synchronization block. This is the first check. After entering the synchronization block, check whether the instance exists again. If it does not exist, create an instance in the case of synchronization. This is the second check. In this way, you only need to synchronize once, thus reducing the time wasted in making judgments multiple times during synchronization.

(4.2) a keyword volatile is used to implement the double check locking mechanism. It means that the value of the variable modified by volatile will not be cached by the local thread, and all the reads and writes to the variable will directly operate on the shared memory, this ensures that multiple threads can correctly process the variable. This implementation method can achieve thread-safe instance creation without too much impact on performance. It is only synchronized when the instance is created for the first time, and does not need to be synchronized in the future, thus speeding up the operation.

3. The Singleton mode prevents other objects from instantiating copies of their own objects, so that all objects can access a unique instance.

4. Because the class in singleton mode controls the instantiation process, the class can modify the instantiation process more flexibly.

 

Iii. Singleton mode in iOS

1. Basic steps:

(1) create a static instance for the singleton object, which can be written as global, implemented in class methods, and initialized as nil;

(2) Implement an instance constructor and check whether the static Instance declared above is nil. If yes, create and return an instance of this class;

(3) rewrite the allocWithZone method to ensure that no new instance is generated when others directly use alloc and init to obtain a new strength;

(4) Implement allocWitheZone, copyWithZone, release, and autorelease as appropriate.

 

1 The following uses ImageStore as an example to describe how to create a singleton mode: 2 3 in ImageStore. in the H file, write the following code: 4 # import <Foundation/Foundation. h> 5 @ interface ImageStore: NSObject 6 {7 NSMutableDictionary * dictionary; 8} 9 + (ImageStore *) defaultImageStore; 10-(void) setImage: (UIImage *) image forKey: (NSString *) string; 11-(UIImage *) imageForKey: (NSString *) string; 12-(void) deleteImageForKey: (NSString *) string; 13 @ end14 15 in ImageStore. m text Write the following code: 16 # import "ImageStore. h "17 static ImageStore * defaultImageStore = nil; 18 @ implementation ImageStore19 // prevent the creation of another instance of this type from 20 + (id) allocWithZone :( NSZone *) zone21 {22 return [self defaultImageStore]; 23} 24 + (ImageStore *) defaultImageStore25 {26 if (! DefaultImageStore) 27 {28 // create a singleton 29 defaultImageStore = [[super allocWithZone: NULL] init]; 30} 31 32 return defaultImageStore; 33} 34-(id) init35 {36 if (defaultImageStore) 37 {38 return defaultImageStore; 39} 40 41 self = [super init]; 42 43 if (self) 44 {45 dictionary = [[NSMutableDictionary alloc] init]; 46} 47 48 return self; 49} 50-(void) setImage :( UIImage *) image forKey :( NSString *) string51 {52 [dictio Nary setObject: image forKey: string]; 53} 54-(UIImage *) imageForKey :( NSString *) string55 {56 return [dictionary objectForKey: string]; 57} 58-(void) deleteImageForKey :( NSString *) string59 {60 if (! String) 61 {62 return; 63} 64 65 [dictionary removeObjectForKey: string]; 66} 67 @ end

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.