The perfect singleton mode under "original" iOS, verified

Source: Internet
Author: User

Online about the iOS singleton mode implementation of the post has been many, there are many versions, there are right there is also wrong. I am in the use of the process is difficult to find a more perfect method, simply write a bar, after the project validation is a more reasonable version.

StaticPrautologinview *s_sharedinstance =Nil;+ (Prautologinview *) shareinstance{@synchronized (self) {if(S_sharedinstance = =Nil) {s_sharedinstance= [[[Selfclass] [ hidealloc] init]; }    }    returns_sharedinstance;}#pragmaMark--#pragmaMark Singleton apis+(ID) hidealloc{return[Super alloc];}+(ID) alloc//completely block out the Alloc function {Nsassert (1==0,@"[prautologinview]please use +shareinstance instead of alloc!"); returnNil;}+ (ID)New{    return[Self alloc];}+ (ID) allocwithzone: (struct _nszone *) zone{@synchronized (self) {if (s_sharedinstance = = nil) {            S_sharedinstance = [Super Allocwithzone:zone];        return s_sharedinstance; }} return nil;}-(ID) Copywithzone: (Nszone *) zone{Nsassert (1==0,@"[Prautologinview]copy is not permitted!");    [Self retain]; returnSelf ;}-(ID) Mutablecopywithzone: (Nszone *) zone{return[self copywithzone:zone];}

The point to note here is that when Allocwithzone is called by default, even if you do not explicitly call alloc or allocwithzone, you need to overload

The perfect singleton mode under "original" iOS, verified

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.