单例模式的简单创建

来源:互联网 发布:网络暴力事例2017 编辑:程序博客网 时间:2024/06/06 04:26

使用的时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;}






0 0
原创粉丝点击