打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
iOS单例的完整写法
原文链接:https://my.oschina.net/zyboy/blog/617435

单例模式在iOS开发中是最为常用的模式之一,在应用这个模式时,单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为。一般情况下,许多人都是按下面的方式写单例模式:

#import "Singleton.h"@implementation Singletonstatic Singleton *shareSingleton = nil;  (instancetype)shareSingleton {    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        shareSingleton = [[self alloc] init];    });    return shareSingleton;}@end

测试一下这种方法可行不:

Singleton *one = [Singleton shareSingleton];    NSLog(@"one = %@", one);    Singleton *two = [Singleton shareSingleton];    NSLog(@"two = %@", two);    Singleton *three = [[Singleton alloc] init];    NSLog(@"three = %@", three);

控制台输出内容:
2015-12-22 15:31:38.230 Singleton[2264:1996979] one = <Singleton: 0x7fe598f4d3c0>
2015-12-22 15:31:38.230 Singleton[2264:1996979] two = <Singleton: 0x7fe598f4d3c0>
2015-12-22 15:31:38.231 Singleton[2264:1996979] three = <Singleton: 0x7fe598edc570>

由此可见,只有调用shareSingleton方法获得的对象是相通的,用alloc init来构造对象的时候,得到的确实不一样的结果。究其原因,当使用alloc init创建对象时,在调用alloc方法时,oc内部会调用allocWithZone这个方法来申请内存,为了避免allocWithZone申请新的内存,可以重写allocWithZone方法,在该方法中调用shareSingleton方法返回单例对象。拷贝对象也是同样的道理。

完整代码如下:

#import "Singleton.h"@implementation Singletonstatic Singleton *shareSingleton = nil;  (instancetype)shareSingleton {    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        shareSingleton = [[super allocWithZone:NULL] init];    });    return shareSingleton;}  (instancetype)allocWithZone:(struct _NSZone *)zone {    return [Singleton shareSingleton];}- (id)copyWithZone:(struct _NSZone *)zone {    return [Singleton shareSingleton];}@end

测试:

Singleton *one = [Singleton shareSingleton];    NSLog(@"one = %@", one);    Singleton *two = [Singleton shareSingleton];    NSLog(@"two = %@", two);    Singleton *three = [[Singleton alloc] init];    NSLog(@"three = %@", three);    Singleton *four = [[Singleton alloc] init];    NSLog(@"four = %@", [four copy]);    Singleton *five = [Singleton new];    NSLog(@"five = %@", five);

结果:
2015-12-22 17:01:52.350 Singleton[2399:2262945] one = <Singleton: 0x7f9e6be4ae30>
2015-12-22 17:01:52.350 Singleton[2399:2262945] two = <Singleton: 0x7f9e6be4ae30>
2015-12-22 17:01:52.351 Singleton[2399:2262945] three = <Singleton: 0x7f9e6be4ae30>
2015-12-22 17:01:52.351 Singleton[2399:2262945] four = <Singleton: 0x7f9e6be4ae30>
2015-12-22 17:01:52.351 Singleton[2399:2262945] five = <Singleton: 0x7f9e6be4ae30>

转载于:https://my.oschina.net/zyboy/blog/617435

来源:https://www.icode9.com/content-4-445101.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Objective
iOS开发单例模式Non
iOS 单例模式
ios中单例模式的一点理解
iOS之单例模式初探
swift实现单例的四种方式
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服