使用设计模式中的Singleton单例模式来开发iOS应用程序

2020-01-14 22:07:45于海丽

下面让我们看一下OC当中的单例模式的写法,首先单例模式在ARCMRC环境下的写法有所不同,需要编写2套不同的代码

可以用宏判断是否为ARC环境#if _has_feature(objc_arc)

复制代码
#else
//MRC
#endif
单例模式- ARC -方法一

 

ARC中单例模式的实现
在 .m中保留一个全局的static的实例

复制代码
 static id _instance;
 //重写allocWithZone:方法,在这里创建唯一的实例(注意线程安全)
 + (instancetype)allocWithZone:(struct _NSZone *)zone
{
    @synchronized(self) {
        if (_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    }
    return _instance;
}
提供1个类方法让外界访问唯一的实例
复制代码
    + (instancetype)sharedInstanceTool{
    @synchronized(self){
        if(_instance == nil){
            _instance = [[self alloc] init];
        }
    }
    return _instance;
}

 

实现copyWithZone:方法

复制代码
  -(id)copyWithZone:(struct _NSZone *)zone{
  return _instance;
  }
我们在sharedInstanceTool,首先检查类的唯一实例是否已经创建,如果就会创建实例并将其返回。而之所以调用super而不是self,是因为已经在self中重载了基本的对象分配的方法,需要借用父类的功能来帮助处理底层内存的分配。