NSOperationQueue的簡單使用過程:
1. 建立一個NSOperationQueue的對象
2. 建立一個NSOperation的對象
3. 將operation加入到NSOperationQueue中
MRC 需要手動釋放
4. release掉operation
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:nil)
object:nil];
[queue addOperation:operation];
/***********************************GCD**************************************************/
//一次性執行
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//code be executed once
});
//延遲調用
double delayInSeconds = 2.0;
dispatch_time_t timer = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds *NSEC_PER_SEC);
dispatch_after(timer, dispatch_get_main_queue(), ^{
//code be executed once after delay
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//code be executed once after delay
});
//自定義queque
dispatch_queue_t fun = dispatch_queue_create("funfun", NULL);
dispatch_async(fun, ^{
// your code
});
MRC 需要釋放
//dispatch_release(fun);
//GCD組 同時進行多個任務,任務完成之後再主線程執行其他任務
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
//your code
});
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
//your code
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//your code
});
//多線程的線程安全
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^{ // 線程鎖 NSLock *lock = [[NSLock alloc] init];[lock lock];
//your code
[lock unlock];
}); dispatch_async(queue, ^{ NSLock *lock = [[NSLock alloc] init];[lock lock];
//your code
[lock unlock];
});