iOS Development-Singleton mode

Source: Internet
Author: User
Tags gcd

Singleton mode is a very common design pattern, the previous article uiapplication is a typical singleton pattern, the singleton understanding of the leaf is very simple, not regardless of if access is always only an instantiated object, define a global shared variable, if the object is empty, initialize an object, If the object already exists, use an object that has already been instantiated. The role of a singleton design pattern is to make an object of this class the only instance in the system, so it is necessary to create the object in a unique way and return the address of the object. Here is a picture of the Apple official website can refer to:

Define a food class, share the same foods, define a static variable, and an instance method:

Static Food *sharedfoodobj=nil;+ (food *) sharedfood{    if (!sharedfoodobj) {        sharedfoodobj=[[food alloc]init];    }    return sharedfoodobj;}

 execute the following code and finally find two instance objects food and Foodnext address are the same:

Food  *food=[food Sharedfood];    Food  *foodnext=[food Sharedfood];    NSLog (@ "shared address:%p-shared Address:%p", Food,foodnext);

If you call the Sharedfood method every time you follow the rules, the singleton pattern is complete, but the object can be instantiated, looking at the following code:

    Food  *food=[food Sharedfood];    Food  *foodinit=[[food Alloc]init];    NSLog (@ "shared address:%p-instance Address:%p", food,foodinit);

Food and Foodinit address is not the same, this time we need to modify the following changes to the method, so that the instantiation of the object's address is the same, this time need to rewrite the Allocwithzone method:

+ (food *) sharedfood{    if (!sharedfoodobj) {        sharedfoodobj=[[super allocwithzone:null]init];    }    return sharedfoodobj;} + (Instancetype) Allocwithzone: (struct _nszone *) zone{    return [self sharedfood];}

If the object needs to be the same object when copying it, you can add a method:

+ (ID) copywithzone: (struct _nszone *) zone{    return [self sharedfood];}

If, in order to ensure that the entity is unique in the case of multithreading, you can add @synchronized at this time, @synchronized is to create a mutex to ensure that no other thread modifies the self object at this time. This is a lock token for objective-c, which prevents the self object from being accessed by other threads at the same time, and acts as a thread protection. A singleton mode or a static variable in an operation class is used more. When two concurrent threads access the same object @synchronized (self) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.

+ (food *) sharedfood{    @synchronized (self) {        if (!sharedfoodobj) {            sharedfoodobj=[[food alloc]init];        }    }    return sharedfoodobj;}

After Apple Mac OS 10.6 and iOS4.0 introduced the GCD, using GCD (Grand Central Dispatch) and arc (Automatic Reference counting) to implement the Singleton, this time we can through Dispatch_ Once simple implementation, the code is as follows:

+ (instancetype) sharedinstance{    static food *sharedfoodobj = nil;    Static dispatch_once_t Oncetoken;    Dispatch_once (&oncetoken, ^{        sharedfoodobj =[[super allocwithzone:null]init];    });        return sharedfoodobj;}

Code in FOOD.M:

////food.m//demo//http://www.cnblogs.com/xiaofeixiang//Created by Keso on 15/ 2/8.//Copyright (c) 2015 Keso. All rights reserved.//#import ' Food.h ' @implementation foodstatic food *sharedfoodobj=nil;+ (food *) sharedfood{if (!shar    Edfoodobj) {Sharedfoodobj=[[super allocwithzone:null]init]; } return sharedfoodobj;} + (ID) copywithzone: (struct _nszone *) zone{return [self sharedfood];} -(ID) Copywithzone: (Nszone *) zone{return self;}    + (instancetype) sharedinstance{static food *sharedfoodobj = nil;    Static dispatch_once_t Oncetoken;    Dispatch_once (&oncetoken, ^{sharedfoodobj =[[super Allocwithzone:null]init];        }); return sharedfoodobj;} + (Instancetype) Allocwithzone: (struct _nszone *) zone{return [self sharedinstance];} @end 

iOS single case through the above way can be achieved, some articles on the web to achieve a single example with seven methods, but since the arc, there are some ways Apple has no need to rewrite, say a digression, yesterday there is a blog Park friends did not change the copy of my article, the article below the Description column also explained ( Blog after personal hard work, if reproduced will be special affirmation, blog does not seek technical surprise four, but seek with the person sharing personal learning knowledge, life learning to improve the use), I was his hard income, plagiarism reprint trouble to leave a link, technical articles technical people see, do a technical person need some bottom line ~

iOS Development-Singleton mode

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.