用dispatch_semaphore_t解决block异步执行返回结果问题
1.这是AFN3.0里边的一段代码.利用的是技术信号的形式,等待异步执行的结果,并将结果返回.
- (NSArray *)tasksForKeyPath:(NSString *)keyPath
{
__block NSArray *tasks = nil;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) {
tasks = dataTasks;
} else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) {
tasks = uploadTasks;
} else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) {
tasks = downloadTasks;
} else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) {
tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"];
}
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore);
return tasks;
}
2.Dispatch Queue没有"取消"这一概念,一旦将处理追加到Dispatch Queue中,就没有办法可将该处理去除,也没有办法可在执行中取消该处理.但是可以使用NSOperationQueue中的取消.