这就是我正在做的。
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://myurl"]]];
dispatch_sync(dispatch_get_main_queue(), ^{
if(!data) {
// data not recieved or bad data. Initiate reachability test
// I have built a wrapper for Reachability class called ReachabilityController
// ReachabilityController also notifies the user for avaibility, UI
ReachabilityController *reachability = [[ReachabilityController alloc] init];
[reachability checkReachability];
return;
}
//update table
});
});
我的问题是可达性测试是在主队列中完成的,这通常会卡住 UI。我想在后台模式下运行。
我想在后台模式或低优先级模式下处理 ReachabilityTest。但同样,我的可达性 Controller 确实会通知用户当前的网络可用性,因此在某些时候我将不得不再次使用主队列。
我坚信一定有更好的方法。
最佳答案
然而,这是一个正确的方法。它看起来并不完全漂亮,但这并不意味着它是错误的。如果您希望您的代码看起来“更干净”,您可能想看看 NSThread
并逐步完成它,但这是一种更简单的方法。
为了使它在我的项目中看起来更容易,我们创建了一个名为调度程序的简单类,它使用 block :
+ (void)dispatchOnBackgroundAsync:(void(^)(void))block {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), block);
}
+ (void)dispatchOnMainAsync:(void(^)(void))block {
dispatch_async(dispatch_get_main_queue(), block);
}
像这样使用:
[Dispatcher dispatchOnBackgroundAsync:^{
// background thread code
[Dispatcher dispatchOnMainAsync:^{
// main thread code
}];
}];
关于ios - 如何将操作从主队列转移到后台释放主队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14337270/