GCD

iOS
  1. 1. GCD 有許多用法,不知道你會那幾種?

GCD 有許多用法,不知道你會那幾種?

1. 背景執行

1
2
3
4
5
6
7
8
let defaultPriority = DISPATCH_QUEUE_PRIORITY_DEFAULT
let backgroundQueue = dispatch_get_global_queue(defaultPriority, 0)
dispatch_async(backgroundQueue, {
let result = doSomeExpensiveWork()
dispatch_async(dispatch_get_main_queue(), {
//use `result` somehow
})
})

2. Singleton

1
2
3
4
5
6
7
8
+ (instancetype) sharedInstance {
static dispatch_once_t onceToken;
static id sharedInstance;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}

3. with blocks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
typealias DoneBlock = () -> ()
typealias WorkBlock = (DoneBlock) -> ()

class AsyncSerialWorker {
private let serialQueue = dispatch_queue_create("ios.taipei.queue", DISPATCH_QUEUE_SERIAL)

func enqueueWork(work: WorkBlock) {
dispatch_async(serialQueue) {
let semaphore = dispatch_semaphore_create(0)
work({
dispatch_semaphore_signal(semaphore)
})
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}
}
}

4. multi-task

1
2
3
4
5
6
7
8
9
dispatch_group_t group = dispatch_group_create()
for item in someArray {
dispatch_group_async(group, backgroundQueue, {
performExpensiveWork(item: item)
})
}
dispatch_group_notify(group, dispatch_get_main_queue(), {
// all the work is complete
}