A probe into the single-case mode of iOS

Source: Internet
Author: User

The singleton pattern is probably the simplest form of design pattern, which is intended to make an object in a Class A unique instance of the system. It provides a global access point to the resources provided by the objects of the class. Therefore, you need a mechanism that only allows you to generate a unique instance of an object class. Let's look at the role of a single example:
    • Guaranteed program run process, one class with only one example, and the instance is easy for the outside world to access
    • Thus, the number of instances is conveniently controlled and system resources are saved.
The use of single-case mode
    • A class can have only one instance, and it must be accessed from a value-based access point.
    • This unique instance can only be extended by subclasses, and the extended object does not break the client code.
The methods are public in objective-c, and the language of OC is a dynamic type, so all classes can send each other's messages. , and the cocoa framework uses a count of memory management methods to maintain the memory lifetime of an object. Let's take a look at the pattern of the singleton in OC, first of all, the singleton pattern is different in ARC\MRC environment, it needs to write 2 sets of different code
    • You can use a macro to determine whether an arc environment
      #if _has_feature(objc_arc)#else//MRC#endif
      Singleton mode-ARC-method one
    • Implementation of single-case mode in Arc
    • Keep an instance of global static in. m
static id _instance; //重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全) +(id)allocWithZone:(struct _NSZone*)zone{ @synchronized(self){ if(_instance){ _instance = [super allocWithZone:zone]; } } } return _instance;
    • Provides 1 class methods for external access to unique instances
 + (instancetype) sharedinstancetool{ @synchronized (self) {if (_instance) {        _instance = [[self alloc] init]; }} return _instance;}       
    • Implementing Copywithzone: Methods

        -(id)copyWithZone:(struct _NSZone *)zone{  return _instance;  }
      We're sharedInstanceTool going to first check if the unique instance of the class has been created, and if it creates an instance and returns it. The reason for calling super rather than self is that you have overloaded the basic object allocation method in self, and you need to borrow the functionality of the parent class to help handle the allocation of the underlying memory. In the allocWithZone:(struct _NSZone*)zone method, only sharedInstanceTool the class instance returned from the method is returned. The same call in the Cocoa framework allocWithZone:(struct _NSZone*)zone allocates memory, the reference count is set to 1, and the instance is returned. The same override (id)copyWithZone:(struct _NSZone *)zone method is also to ensure that the instance's copy is not returned, but instead returns self. Returns the same instance.
Thread safety. In the above example we pass @synchronizedTo add a mutex to ensure thread safety. And now we're going to try to implement a single example of a single order in a threaded way.
static wmobject *_instance;+ (instancetype) Allocwithzone: ( struct _nszone *) zone{static  dispatch_once_t Oncetoken; dispatch_once (&oncetoken, ^{_instance = [super Allocwithzone:zone]; }); return _instance;} + (instancetype) sharedinstance{static dispatch_once_t Oncetoken; dispatch_once (&oncetoken, ^{_instance = [[self alloc] INIT]; }); return _instance;} -(id) Copywithzone: (nszone *) zone{ return _instance;}           
From the above code we can see that the realization of the idea is basically consistent with our sharedInstanceTool, first checks whether the unique instance of the class has been created, and if it creates an instance and returns it. And a slightly different place is where we pass this time. dispatch_once_tTo ensure the security of the thread. As for dispatch_once_tThe usage here is one by one, the thread of the relevant tutorials will have its related description. Here a simple singleton pattern is basically implemented, so we can try to encapsulate it in a macro and then make it easier for later calls to create a WMSingleton.h
. h file#define WMSINGLETONH (name) + (instancetype) shared##name;//. m file#define WMSINGLETONM (name)Static ID _instance; + (Instancetype) Allocwithzone: (struct _nszone *) zone{Static dispatch_once_t Oncetoken;Dispatch_once (&oncetoken, ^{_instance =[Super Allocwithzone:zone]; });return _instance;} + (Instancetype) gkfx##name{ static dispatch_once_t Oncetoken; dispatch_once (&oncetoken, ^{ _instance = [[Self alloc] init];  }); return _instance; }  -(ID) Copywithzone: (Nszone *) zone { return _instance; }
How to use
//.h类//引入这个宏文件#import "WMSingleton.h"@interface WMObject : NSObjectWMSingletonH(object)@end//.m类@implementation WMObjectWMSingletonM(Car)@end
Through the walkthroughs above, we basically learned some basic singleton patterns and then Cocoa TouchThere is also a large number of singleton patterns in the framework that allow us to learn, such as UIApplicationUIAccelerometerAnd NSFileManagerWait a minute. So in the single-instance mode of learning is still a heavy task ...

A probe into the single-case mode of iOS

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.