iOS 单例的写法

关于什么是单例,iOS中的单例模式是什么,自行爬页搜索。这里抛砖引玉,说说单例模式应该怎样实现。

直接上代码。

//
//  Singleton.h
//  SingletonDemo
//
//  Created by WangBo on 3/9/16.
//  Copyright © 2016 WangBo. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Singleton : NSObject

+ (instancetype)shareInstance;

@end


//
//  Singleton.m
//  SingletonDemo
//
//  Created by WangBo on 3/9/16.
//  Copyright © 2016 WangBo. All rights reserved.
//

#import "Singleton.h"

@implementation Singleton

static Singleton *_singleton = nil;

+ (instancetype)shareInstance {
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
      _singleton = [[super allocWithZone:NULL] init];//调用super的allocWithZone方法,是因为self的该方法在下面被重载了
    });
    return _singleton;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
    return [self shareInstance];
}

+ (id)copyWithZone:(struct _NSZone *)zone {
    return [self shareInstance];
}

@end


//
//  main.m
//  SingletonDemo
//
//  Created by WangBo on 3/9/16.
//  Copyright © 2016 WangBo. All rights reserved.
//

#import "Singleton.h"
#import <Foundation/Foundation.h>

int main(int argc, const char *argv[]) {
    @autoreleasepool {
        // insert code here...
        Singleton *singleton1 = [Singleton shareInstance];
        NSLog(@"%@", singleton1);
        Singleton *singleton2 = [Singleton shareInstance];
        NSLog(@"%@", singleton2);
        Singleton *singleton3 = [Singleton shareInstance];
        NSLog(@"%@", singleton3);
    }
    return 0;
}


程序输出:

2016-03-09 19:27:31.375 SingletonDemo[11477:206113] <Singleton: 0x100302340>
2016-03-09 19:27:31.376 SingletonDemo[11477:206113] <Singleton: 0x100302340>
2016-03-09 19:27:31.376 SingletonDemo[11477:206113] <Singleton: 0x100302340>
Program ended with exit code: 0

我们可以看到,三个对象对应内存中同一个值。


说明:

1.之所以要重载allocWithZone、copyWithZone方法,是因为如果不这样做,客户端通过这两个方法会得到一个新的实例,违背了我们单例模式的思想;

2.本文使用dispatch_once函数实现单例Singleton的初始化,因此只会在程序运行周期中执行一次,保重了单例的单一性。同时满足了线程安全的要求。

3.考虑到线程安全,我们同样可以使用对self加锁的方式来实现,@synchronized、NSLock,自行爬文搜索。


收工!~



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值