iOS单例建立

在objective-c中要实现一个单例类,至少须要作如下四个步骤:objective-c

  一、为单例对象实现一个静态实例,并初始化,而后设置成nil,spa

  二、实现一个实例构造方法检查上面声明的静态实例是否为nil,若是是则新建并返回一个本类的实例,code

  三、重写allocWithZone方法,用来保证其余人直接使用alloc和init试图得到一个新实力的时候不产生一个新实例,对象

  四、适当实现allocWitheZone,copyWithZone,release和autorelease。it

下面是一个简单的例子:io

static XYLocationManager *sharedInstance = nil;
+ (XYLocationManager *)sharedInstance{
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        if (sharedInstance == nil) {
            sharedInstance = [[self alloc] init];
        }
    });
   
    return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
   
    @synchronized(self) {
       
        if (sharedInstance == nil) {
            sharedInstance = [super allocWithZone:zone];
        }
        return sharedInstance;
    }
    return nil;
}
- (id)copyWithZone:(NSZone *)zone {
   
     return self;
}
- (id)init {
   
    @synchronized(self) {
        self = [super init];
       
        return self;
    }
}
相关文章
相关标签/搜索