iOS单例的完整写法

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

#import "Singleton.h"

@implementation Singleton

static 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 Singleton

static 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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值