首页 > 其他 > 详细

OC 单例

时间:2015-06-10 01:04:03      阅读:119      评论:0      收藏:0      [点我收藏+]

1利用GCD方式实现单例(ARC)

#import "People.h"

@implementation People
static id _instace;
+(id)allocWithZone:(struct _NSZone *)zone{ //为防止用alloc创建对象
    
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _instace=[super allocWithZone:zone];
        
    });
    
    return _instace;
}

+(id)shareInstace{
    
    
    if (_instace==nil) {
        
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{     //dispatch_once 里的代码块只会执行一次
            
            _instace=[[self alloc]init];
            
        });
    }
    
    return self;
    
}


-(id)copyWithZone:(NSZone*)zone{ //为防止用alloc创建对象
    
    
    return _instace;
    
}

@end

 

 

2利用GCD方式实现单例(非ARC)

@implementation People

static id _instace;

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instace = [super allocWithZone:zone];
    });
    return _instace;
}

+ (instancetype)sharedDataTool
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instace = [[self alloc] init];
    });
    return _instace;
}

- (id)copyWithZone:(NSZone *)zone
{
    return _instace;
}

- (oneway void)release {

}
- (id)retain {
    
    
    return self;

}
- (NSUInteger)retainCount {
    
    return 1;

}
- (id)autorelease {
    
    return self;

}

@end

 

OC 单例

原文:http://www.cnblogs.com/mgy007/p/4564931.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!