OC 单例

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

 

posted on 2015-06-09 23:52  MGY007  阅读(655)  评论(0编辑  收藏  举报