单例模式

单例模式-ARC 

1.在.m中保留一个全局的static的实例

static id _instance;

2.重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)

+ (id)allocWithZone:(struct _NSZone *)zone
{
    @synchronized(self) {
        if (!_instance) {
            _instance = [super allocWithZone:zone];
        }
    }
    return _instance;
}

 3.提供1个类方法让外界访问唯一的实例

+ (instancetype)sharedSoundTool
{
    @synchronized(self) {
        if (!_instance) {
            _instance = [[self alloc] init];
        }
    }
    return _instance;
}

4.实现copyWithZone:方法

+ (id)copyWithZone:(struct _NSZone *)zone
{
    return _instance;
}

单例模式 – MRC

非ARC中(MRC),单例模式的实现(比ARC多了几个步骤) 

实现内存管理方法

- (id)retain { return self; }
- (NSUInteger)retainCount { return 1; }
- (oneway void)release {}
- (id)autorelease { return self; }


你可能感兴趣的:(单例模式)