单例模式的简单创建

使用的时GCD中的dispatch_once 方法和block结合使用


//Singleton.h
@interface Singleton : NSObject
+ (Singleton *)sharedSingleton; //1、创建类方法
@end
 
/***************************************************************/
 
//Singleton.m
#import "Singleton.h"
@implementation Singleton   
static Singleton *sharedSingleton = nil;//2、声明一个static实例变量
 
+ (Singleton *)sharedSingleton{
    static dispatch_once_t once;//定义只实现一次的方法
    dispatch_once(&once,^{
        sharedSingleton = [[self alloc] initPrivate];//4、在block中对声明的static实例进行操作
        //dosometing
    });
    return sharedSingleton;//5、返回static实例
} 

//不允许调用init方法,调用时提示错误信息和应该使用的方法
- (instancetyoe)init{
    @throw [NSException exceptionWithName:@"singleton"] reason:@"Use  [Singleton sharedSingleton] instead" userInfo:nil];
    return nil;
}

- (instancetype)initPrivate{
    self = [super init];
    if(self){
       //do something such as lazy-load 
    }
    return self;
}




 
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值