dispatch_sync(dispatch_queue_t queue, dispatch_block_t block);程序員
dispatch_async(dispatch_queue_t queue, dispatch_block_t block);安全
dispatch_queue_t dispatch_get_global_queue(多線程
dispatch_queue_priority_t priority, // 隊列的優先級併發
unsigned long flags); // 此參數暫時無用,用0便可異步
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 得到全局併發隊列async
dispatch_queue_t函數
dispatch_queue_create(const char *label, // 隊列名稱 spa
dispatch_queue_attr_t attr); // 隊列屬性,通常用NULL便可線程
dispatch_queue_t queue = dispatch_queue_create("cn.itcast.queue", NULL); // 建立orm
dispatch_release(queue); // 非ARC須要釋放手動建立的隊列
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 執行耗時的異步操做...
dispatch_async(dispatch_get_main_queue(), ^{
// 回到主線程,執行UI刷新操做
});
});
[self performSelector:@selector(run) withObject:nil afterDelay:2.0];
// 2秒後再調用self的run方法
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 2秒後異步執行這裏的代碼...
});
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// 只執行1次的代碼(這裏面默認是線程安全的)
});
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 執行1個耗時的異步操做
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 執行1個耗時的異步操做
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
// 等前面的異步操做都執行完畢後,回到主線程...
});
#if __has_feature(objc_arc)
// ARC
#else
// MRC
#endif
static id _instance;
+ (id)allocWithZone:(struct _NSZone *)zone
{
@synchronized(self) {
if (!_instance) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
+ (instancetype)sharedSoundTool
{
@synchronized(self) {
if (!_instance) {
_instance = [[self alloc] init];
}
}
return _instance;
}
+ (id)copyWithZone:(struct _NSZone *)zone
{
return _instance;
}
- (id)retain { return self; }
- (NSUInteger)retainCount { return 1; }
- (oneway void)release {}
- (id)autorelease { return self; }