The application of single case is very common, and the singleton mode makes one instance of a class.
*easy access for the outside world.*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! Therefore, in this method, use the"dispatch_once", to ensure that theMultithreadingin which_instancecan only be "allocated" once space.*3.Define asharedxxx "Class "Methodto make it easy for other objects that use a singleton to invoke this singleton.in this method, you also use the"dispatch_once", ensure that objects that use the class method call are initialized only once! Notes: If you do not considercopy& MRC, the above three steps can be! *4.If you want to supportCopy, you need:(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.need tocombine its object Life weeka few ways to write a single case .
*Why to useDispatch_one? :PreventMultithreadingin the meantime .,is quite withJavain a single caseLocking mechanism,guaranteed to be instantiated only once.but it's not used here.synchronized,something like a mutex., but his performance is higher than his.
the code for implementing the single example in arc is as follows:
@implementation xnsharetool/** steps: 1. A static variable _inastance 2. Rewrite allocwithzone, use dispatch_once inside, and call Super Allocwithzone 3. Customize a sharedxx to get the singleton. In the inside also call Dispatch_once, instantiate _instance-----------optional------------4. If you want to support copy. Rewrite the Copywithzone (followed by the Nscopying protocol) and return directly to the _instance. *//** 1th Step: Store A unique instance */static xnsharetool *_instance;/** 2nd step: Allocating memory holes This method is called when the home is allocated. 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 multiple threads dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{ _instance = [Super Allocwithzone:zone]; }); return _instance;} /** the 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: Make sure copy is the same */-(ID) Copywithzone: (Nszone *) zone{ return _instance;} @end
The test code is as follows (printing the Singleton object'sThe addresses are 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 inMRCindon't needby Programmersto manage,so we're going to cover someMemoryMethods of Management.
implementation part andARCconsistent,only needcoversomeMRCinMemoryManagementmethod of:*- (ID) retain.no additional reference counters are required in the singleton.returnSelf .*-(ID) autorelease.only objects in the heap need.not required in a single case. ReturnSelf .*-(Nsuinteger) Retaincount.(can write not write,prevent misunderstanding).There is no need to modify the reference count in the singleton and return the largest unsigned integer. return Uint_max;*-(OneWay void) Release.don't 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;} Not required-(OneWay void) Release {}//does not require the number of counters. Returns the maximum unsigned integer directly-(Nsuinteger) Retaincount {return uint_max; Retaincount} referencing a constant area string @end
Iii. Integration of Arc and MRC
integration is to facilitate a single caseCan be used in arc and in MRC. Instead of having to modify the methods in the singleton.
the practice is to use a macro definition: (to determine whether the ARC environment, yes, 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 integrates ======================================= #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