创建只执行一次的代码块
使用dispatch_once
上例子
@implementation AppDelegate
static dispatch_once_t onceToken;
void (^executedOnlyOnce)(void) = ^{
static NSUInteger numberOfEntries = 0;
numberOfEntries++;
NSLog(@"Executed %lu time(s)", (unsigned long)numberOfEntries);
};
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
dispatch_queue_t concurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_once(&onceToken, ^{
dispatch_async(concurrentQueue,
executedOnlyOnce);
});
dispatch_once(&onceToken, ^{
dispatch_async(concurrentQueue,
executedOnlyOnce);
});
// Override point for customization after application launch.
return YES;
}
结果他只执行了一次
2014-03-06 15:00:47.888 cookbook6_7[539:1403] Executed 1 time(s)
gcd在第一次执行时生成onceToken,往后发现onceToken已经有了就不在执行了。
看看dispatch_once_t是什么
/*!
* @typedef dispatch_once_t
*
* @abstract
* A predicate for use with dispatch_once(). It must be initialized to zero.
* Note: static and global variables default to zero.
*/
typedef long dispatch_once_t;
所以以后单例模式可以这样来创建了
#import "MySingleton.h"
@implementation MySingleton
- (id) sharedInstance{
static MySingleton *SharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{
SharedInstance = [MySingleton new]; });
return SharedInstance; }
@end