Creating a singleton class

Source: Internet
Author: User

#import "SingalTon.h"

@implementation Singalton

Instance variables cannot be used in static methods

Need to be defined as a global variable or a static variable

Static Singalton * _singleton=nil;

+ (Singalton *) Sharesingleton

{

Before returning an object, it is necessary to determine whether the object was created before, and if it is not created, it is necessary to create an object that, if created , returns the last object created.

When multiple threads access the Singleton class at the same time, multiple singleton classes are created , and a lock is required ;

@synchronized(self)

{

if (_singleton = = nil)

{

_singleton=[[self alloc]init];

}

}

return _singleton;

}

You need to override the Alloc method to ensure that other users create and create only one object when using the Alloc method

+ (ID) alloc

//{

@synchronized (self)

//    {

if (_singleton==nil)

//        {

_singleton=[super Alloc];

//        }

//

//    }

return _singleton;

//}

The allocwithzone method is called inside the Alloc method

The Alloc method is not called when using the Allocwithzone method , so just rewrite it with Allocwithzone.

+ (ID) allocwithzone: (struct _nszone *) zone

{

@synchronized(self)

{

if (_singleton==nil)

{

_singleton=[Super Allocwithzone:zone];

}

}

return _singleton;

}

if in MRC ( Manual memory Management) , the object is a copy retain release autorelease these operations

/*-(ID) retain

{

return _singleton;

}

-(void) Release

{

}

-(ID) autorelease

{

return _singleton;

}

-(ID) copy

{

return _singleton;

}

-(Nsuinteger) Retaincount

{

return 1;

}*/

Initialization of Appdeledate directly with Alloc and invocation of the Singleton class method initialization will be the same address/object

Creating a singleton class

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.