使用dispatch_once单例进行项目开发

来源:互联网 发布:光棍节程序员闯关 编辑:程序博客网 时间:2024/06/05 02:44

相信大家用的比较多的单利开发方式是,if([super init])这种类型的,判断是否初始化。但是忽略啦一种比较简单安全的GCD单利开发模式。

dispatch_once:

该函数是:

dispatch_once
void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);
该函数使用方法是:

有一个

WCHeartAlertView类。

static  WCHeartAlertView *staic_DRHeartAlertView = nil;+ (id)sharedInstance{        static dispatch_once_t onceToken;    dispatch_once(&onceToken,                  ^{                      staic_WCHeartAlertView = [[WCHeartAlertView alloc] init];                                        });    return staic_WCHeartAlertView;}

只会初始化一次这个类。
之后使用直接就:
WCHeartAlertView *<span style="font-family: Arial, Helvetica, sans-serif;">HeartAlertView=[</span><span style="font-family: Arial, Helvetica, sans-serif;">WCHeartAlertView </span><span style="font-family: Arial, Helvetica, sans-serif;">sharedInstance</span><span style="font-family: Arial, Helvetica, sans-serif;">];</span>



0 0
原创粉丝点击