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

Source: Internet
Author: User

The application of single case is very common, and the singleton mode makes one instance of a class.

* Easy access to the outside world. * Easy to control the number of instances, saving system resources. *oc in theCommon Single Cases: such as: UIApplication, Nsnotificationcenter, Nsuserdefaults, Nsfilemanager. * Applications used in the single example: background music, sound management and so on.

One, the realization of single-case arc

steps to create a single case:* 1. Defines a global static variable _instance, which is used to record objects that are instantiated "first time". * *. Override the Allocwithzone method, which is a method that allocates memory space for an object that must be called! Therefore, the use of "dispatch_once" in this method guarantees that the _instance can only be "allocated" once in multi-threading. *. Defines a sharedxxx "class" method that makes it easy for other objects that use a singleton to invoke this singleton. In this method, the same use " Dispatch_once ", guaranteed to use the class method call object, will only be initialized once! Note: If you do not consider copy& MRC, the above three steps can be! If you want to support copy, you need to: (1) comply with the Nscopying Protocol (2) in the Copywithzone method, return directly to _instance

Tips

* General wording (lazy, a hungry man, locking): if (!_instance) _instance=[[xnsharetoolalloc]init];return_instance;* lazy type is Thread not secure. So it's not written in practice. There are a hungry man, locking and so on. * But OC has its own wording. You need to write a singleton with some methods that combine its object life cycle. * Why use Dispatch_one? : Prevent multithreading at the same time, it is quite with the Java single-instance locking mechanism, guaranteed to be instantiated only once. But it's not synchronized, it's something like a mutex, but it's higher than his performance. The code for implementing the single example in arc is as follows:
@implementationXnsharetool/** Steps: 1. A static variable _inastance 2. Rewrite allocwithzone, use dispatch_once inside, and call Super Allocwithzone 3. Customize a sharedxx to get a 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 Unique instances*/StaticXnsharetool *_instance;/** 2nd step: Allocating memory holes This method is called when the home is allocated. Ensure the same memory Alloc*/+(ID) Allocwithzone: (struct_nszone *) zone{//call Dispatch_once guaranteed to be instantiated only once in multiple threads    Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instance=[Super Allocwithzone:zone];    }); return_instance;}/** 3rd Step: Make sure Init is the same when initializing*/+(instancetype) sharedtool{Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instance=[[Xnsharetool alloc] init];    }); return_instance;}/** 4th step: Make sure the copy is the same*/-(ID) Copywithzone: (Nszone *) zone{return_instance;}@end

The test code is as follows ( the address of the printed singleton object is the same ):

-(void) viewdidload{//Several methods of instantiating a class. The singleton is to ensure that the instantiated class 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 MethodsXnsharetool *T3 =[Xnsharetool Sharedtool]; //3.copyXnsharetool *T4 =[T3 copy]; NSLog (@"%@ %@ %@ %@", T1, T2, T3, T4);}

Second, the use of single example MRC

Because singleton objects are marked with static, they are stored in a static area. So there's no need for programmers to manage it in the MRC, so we're going to overwrite some memory management methods.  The implementation section is consistent with arc, and only needs to overwrite some of the memory management methods in the MRC: *-(ID) retain.  There is no need to increase the reference counter in the Singleton. returnself.*-(ID) autorelease. Only objects in the heap are required. returnself.*-(Nsuinteger) Retaincount is not required in a singleton. (Can write not write, prevent misunderstanding). You do not need to modify the reference count in the singleton to return the largest unsigned integer. return uint_max;*-(OneWay void) release. No release required. Direct coverage, life is not done.
#import "XNShareTool.h"@implementationXnsharetoolStaticXnsharetool *_instance;+ (ID) Allocwithzone: (struct_nszone *) Zone {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instance=[Super Allocwithzone:zone];    }); return_instance;}+(instancetype) Sharedtool {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instance=[[Xnsharetool alloc] init];    }); return_instance;}- (ID) Copywithzone: (Nszone *) Zone {return_instance;}#pragmaMethods that need to be covered in MARK-MRC//No counter required +1- (ID) Retain {returnSelf ;}//not required. The objects of the heap area need only- (ID) Autorelease {returnSelf ;}//don't need-(OneWayvoid) Release {}//The number of counters is not required. Return the maximum unsigned integer directly-(Nsuinteger) retaincount {returnUint_max;//referencing the retaincount of a constant area string}@end

Iii. Integration of Arc and MRCThe integration is designed to facilitate the use of the single case both 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 Integrated =======================================#pragmaMethods to be covered in MARK-MRC, integration of Arc and MRC#if!__has_feature (OBJC_ARC)-(ID) Retain {returnSelf ;}- (ID) Autorelease {returnSelf ;}-(OneWayvoid) Release {}-(Nsuinteger) retaincount {returnUint_max;}#endif//============================================================================

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.