单例类的创建

#import "SingalTon.h"

 

@implementation SingalTon

//实例变量不能在静态方法中使用

//需要定义成全局变量或者静态变量

static  SingalTon * _singleTon=nil;

+(SingalTon *) ShareSingleTon

{

//    返回对象前需要判断,这个对象之前是否创建过,如果没有创建过,就需要创建一个对象,如果创建过,就把上一次创建的对象返回出去

    

// 多个线程同时访问单例类时,就会创建多个单例类,就需要加锁;

    @synchronized(self)

    {

        if (_singleTon == nil)

        {

            _singleTon=[[self alloc]init];

        }

 

    }

        return _singleTon;

}

//需要重写alloc方法,保证其他用户在使用alloc方法时候创建,也只创建一个对象

//+(id)alloc

//{

//    @synchronized(self)

//    {

//        if (_singleTon==nil)

//        {

//            _singleTon=[super alloc];

//        }

//

//    }

//        return _singleTon;

//}

//在alloc方法内部会调用allocWithZone这个方法

//使用allocWithZone方法时候不调用alloc方法,所以只用对allocWithZone进行重写就好

+(id)allocWithZone:(struct _NSZone *)zone

{

    @synchronized(self)

        {

            if (_singleTon==nil)

            {

                _singleTon=[super allocWithZone:zone];

            }

    

        }

            return _singleTon;

}

 

//如果在MRC(手动内存管理) 中, 对象是有 copy retain release autorelease 这些操作的

/*-(id)retain

{

    return _singleTon;

}

-(void)release

{

    

}

-(id)autorelease

{

    return _singleTon;

}

-(id)copy

{

    return _singleTon;

}

-(NSUInteger)retainCount

{

    return 1;

}*/

在appdeledate直接使用alloc初始化和调用单例类方法初始化将是同一个地址/对象

原文地址:https://www.cnblogs.com/wangzhen-Me/p/4844797.html