A single case and its application under "IOS" ARC-MRC

Source: Internet
Author: User

The application of singleton is very common, and the Singleton pattern makes a class have only one instance .

*easy access to external questions.*easy to control the number of instances,Conserve system resources.
*OCin theCommon Single Cases:such as: UIApplication,  Nsnotificationcenter,  Nsuserdefaults,Nsfilemanager.
*the singleton used in the application:such as: background music. Sound management, and more.


One, the realization of single-case arc

to create a single case : *1.Define aGlobal static variables_instance, which is used to record the "first time" object that was instantiated..*2.rewriteAllocwithzoneMethod, this method is a method that allocates memory space for an object that must be called! so. In this method, use the"dispatch_once", you can guarantee theMultithreadingin which_instancecan only be "allocated" one space.*3.Define asharedxxx "Class "Method. Facilitates the invocation of this singleton by other objects that use a single instance.in this method, the same use"dispatch_once", the object that is invoked with the class method is guaranteed to be initialized only once. Gaze: Suppose not to considercopy& MRC, the above three steps will be possible! *4.Suppose you want to supportCopy, you need to:(1)comply withnscopyingProtocol(2)in theCopywithzonemethod, return directly to the_instance


Tips

*the general wording(Lazy Type,a hungry man type,Locking):if (!_instance)_instance=[[XnsharetoolAlloc]Init];return_instance;*Lazy Type isThread not secureof the.so it's not actually written.. and a A hungry man-style .,Locking, etc..
*butOChas its own wording in the.needcombine its object Life weeka few ways to write a single case .
*Why to useDispatch_one?

: prevent multithreading come in at the same time java in a single case plus lock mechanism guaranteed to be instantiated only once But it's not used here SYNCHRONIZED,  ,  But higher than his performance
arc to implement a singleton code such as the following:

@implementation xnsharetool/** steps: 1. A static variable _inastance 2. Rewrite allocwithzone, use dispatch_once inside, and call Super Allocwithzone 3. Define yourself a sharedxx to get the singleton. In the inside also call Dispatch_once, instantiate _instance-----------Optional------------4. Assume that you want to support copy. Rewrite the Copywithzone (nscopying protocol) and return directly to _instance.   *//** 1th Step: Store A unique instance */static xnsharetool *_instance;/** 2nd step: Allocating memory holes Home will call this method. Ensure that the allocation of memory Alloc is the same */+ (ID) allocwithzone: (struct _nszone *) zone{    //Call dispatch_once ensure that only one static is instantiated in multi-threading    dispatch_once_t Oncetoken;    Dispatch_once (&oncetoken, ^{        _instance = [Super Allocwithzone:zone];    });    return _instance;} /** 3rd step: Ensure that init initialization is the same */+ (instancetype) sharedtool{    static dispatch_once_t Oncetoken;    Dispatch_once (&oncetoken, ^{        _instance = [[Xnsharetool alloc] init];    });    return _instance;} /** 4th step: Ensure that copy is the same */-(ID) Copywithzone: (Nszone *) zone{    return _instance;} @end

Test code such as the following (printing a singleton object'sThe address is the same):

-(void) viewdidload{    //Instantiate several methods of a class. The singleton is to ensure that the class that is instantiated is the same class    //1.alloc init method. Generally not so to invoke a singleton.    Xnsharetool *t1 = [[Xnsharetool alloc] init];    Xnsharetool *t2 = [[Xnsharetool alloc] init];        2. Class method    Xnsharetool *t3 = [Xnsharetool sharedtool];        3.copy    Xnsharetool *t4 = [T3 copy];        NSLog (@ "%@%@%@%@", T1, T2, T3, T4);}


second, the use of single example MRC


becausesingle-instance objectsis to useStatictagged,therefore stored inStatic Zone.so inMRCinno needby the program apeto manage,so we're going to cover someMemoryMethods of Management.
implementation part andARCconsistent,just needcoversomeMRCinMemoryManagementmethod of:*- (ID) retain.There is no need to add a reference counter in a single case.returnSelf .*-(ID) autorelease.Only objects in the heap need to be.in a single case, there is no need. ReturnSelf .*-(Nsuinteger) Retaincount.(can write not write,prevent misunderstanding).There is no need to change the reference count in a single case. Returns the largest unsigned integer to. return Uint_max;*-(OneWay void) Release.no needrelease.Direct Coverage,life doesn't do it..
#import "XNShareTool.h" @implementation xnsharetoolstatic xnsharetool *_instance;+ (ID) allocwithzone: (struct _nszone * Zone {static dispatch_once_t oncetoken;dispatch_once (&oncetoken, ^{    _instance = [Super Allocwithzone:zone];}); return _instance;} + (Instancetype) sharedtool {static dispatch_once_t oncetoken;dispatch_once (&oncetoken, ^{    _instance = [[ Xnsharetool alloc] init];}); return _instance;} -(ID) Copywithzone: (Nszone *) zone {return _instance;} #pragma the method that needs to be overwritten in MARK-MRC//Do not need counter +1-(ID) retain {return self;} No need. The object of the heap area is required-(ID) autorelease {return self;} No-(OneWay void) Release {}//does not require the number of counters. Returns the maximum unsigned integer directly-(Nsuinteger) Retaincount {return uint_max;  Retaincount} @end of the normal volume string

Iii. Integration of Arc and MRC
integration is to facilitate a single caseCan be used in arc and in MRC。

Instead of having to change the methods in the singleton.
The detailed approach is to use a macro definition: (infer if it is an arc environment, then omit the memory management method)

#if!__has_feature (OBJC_ARC)

The method of memory management in MRC is placed in this place

#endif

The code is as follows:

=============================ARC/MRC Integrated ======================================= #pragma the methods that need to be covered in the MARK-MRC, Integration of Arc and MRC # if!__has_feature (OBJC_ARC)-(ID) retain {return self;} -(ID) autorelease {return self;} -(OneWay void) Release {}-(Nsuinteger) Retaincount {return uint_max;} #endif//============================================================================


Reprint Please specify the Source:http://blog.csdn.net/xn4545945  





A single case and its application under "IOS" ARC-MRC

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.