IOS Singleton Mode

Source: Internet
Author: User

IOS Singleton Mode

In the afternoon, I helped my colleagues change the code for one afternoon. I was deeply stabbed and deeply felt the importance of the Code architecture. I felt that the design model should be well polished. As a result, let's look at the design pattern from easy to difficult. Let's start with the simplest Singleton pattern of iOS.

As the simplest design mode of iOS-singleton mode, the main function is to ensure that a class only has a unique instance in the project. Saves resources and reduces unnecessary expenses.

How to Create a Singleton?

Define a global variable:
static Singleton * _instance =nil;
Provides a class method interface for external calls:
+(instancetype)shareInstance{    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{    _instance =[[super allocWithZone:NULL]init];    });    return _instance;}
Override System Call Method

When instantiating an object, we usually use the alloc, init, or copy method. When we call the alloc method, OC calls the allocWithZone method internally to apply for memory. The same principle applies to copying objects. The OC calls the copyWithZone method internally. Therefore, we need to rewrite these two methods to ensure the singularity of the instance:

+(instancetype)allocWithZone:(struct _NSZone *)zone{      return [Singleton shareInstance];}-(instancetype)copyWithZone:(struct _NSZone *)zone{      return [Singleton shareInstance];}

Let's call:

    Singleton *obj1=[Singleton shareInstance];    NSLog(@"obj1=%@",obj1);    Singleton *obj2=[Singleton shareInstance];    NSLog(@"obj2=%@",obj2);    Singleton *obj3=[[Singleton alloc]init];    NSLog(@"obj3=%@",obj3);    Singleton *obj4=[[Singleton alloc]init];    NSLog(@"obj4=%@",[obj4 copy]);

If the printed result address is the same, the result is as follows:

2016-03-04 18:26:00.204  obj1=
  
   2016-03-04 18:26:00.205  obj2=
   
    2016-03-04 18:26:00.205  obj3=
    
     2016-03-04 18:26:00.205  obj4=
     
    
   
  

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.