iOS 单例篇

栏目: IOS · 发布时间: 6年前

内容简介:直接告诉外面 alloc、new、copy、mutableCopy方法不可以直接调用,否则编译不过。

ARC中单例实现步骤

  • 在类的内部提供一个static修饰的全局变量
  • 提供一个类方法,方便外界访问
  • 重写 +allocWithZone 方法,保证永远都只为单例对象分配一次内存空间
  • 严谨起见,重写 -copyWithZone 方法和 -MutableCopyWithZone 方法

ARC中单例代码实现

#import "Tools.h"

@implementation Tools
// 创建静态对象 防止外部访问
static Tools *_instance = nil;
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    //    @synchronized (self) {
    //        // 为了防止多线程同时访问对象,造成多次分配内存空间,所以要加上线程锁
    //        if (_instance == nil) {
    //            _instance = [super allocWithZone:zone];
    //        }
    //        return _instance;
    //    }
    // 也可以使用一次性代码
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    });
    return _instance;
}
// 为了使实例易于外界访问 我们一般提供一个类方法
// 类方法命名规范 share类名|default类名|类名
+(instancetype)shareTools{
    //return _instance;
    // 最好用self 用Tools他的子类调用时会出现错误
    return [[self alloc] init];
}
// 为了严谨,也要重写copyWithZone 和 mutableCopyWithZone
-(id)copyWithZone:(NSZone *)zone{
    return _instance;
}
-(id)mutableCopyWithZone:(NSZone *)zone{
    return _instance;
}
复制代码

2. 单例在MRC中的实现

MRC单例实现步骤

  • 在类的内部提供一个static修饰的全局变量
  • 提供一个类方法,方便外界访问
  • 重写 +allocWithZone 方法,保证永远都只为单例对象分配一次内存空间
  • 严谨起见,重写 -copyWithZone 方法和 -MutableCopyWithZone 方法
  • 重写release方法
  • 重写retain方法
  • 建议在retainCount方法中返回一个最大值

配置MRC环境

  • 注意ARC不是垃圾回收机制,是编译器特性
  • 配置MRC环境:build setting ->搜索automatic ref->修改为N0 MRC中单例代码实现
  • 配置好MRC环境之后,在ARC代码基础上重写下面的三个方法即可
-(oneway void)release{
    
}
-(instancetype)retain{
    return _instance;
}
-(NSUInteger)retainCount{
    return MAXFLOAT;
}
复制代码

3. 单例的另一种实现

直接告诉外面 alloc、new、copy、mutableCopy方法不可以直接调用,否则编译不过。

+ (instancetype)alloc __attribute__((unavailable("call sharedInstance instead")));
+ (instancetype)new __attribute__((unavailable("call sharedInstance instead")));
- (instancetype)copy __attribute__((unavailable("call sharedInstance instead")));
- (instancetype)mutableCopy __attribute__((unavailable("call sharedInstance instead")));
复制代码

附:我的博客地址


以上所述就是小编给大家介绍的《iOS 单例篇》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

匠心体验

匠心体验

[法] 艾米丽·布歇 / 吴 博 / 人民邮电出版社 / 2016-11 / 69.00元

本书针对在智能手机和平板电脑的网站及应用程序设计,详细剖析了移动终端服务的用户体验设计要点,阐述了营造舒适的感官体验、甄选内容及功能、提高用户效率、优化等待时间、合理实施教学、情感设计等方面的设计诀窍,并通过大量实例,呈现当今移动终端服务设计中的亮点与雷区。一起来看看 《匠心体验》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试