我完全按照您使用NSOperationQueue
. 首先,创建一个串行队列并默认挂起它:
self.operationQueue = [[[NSOperationQueue alloc] init] autorelease];
self.operationQueue.maxConcurrentOperationCount = 1;
[self.operationQueue setSuspended:YES];
然后,创建一个 Reachability 实例并注册kReachabilityChangedNotification
:
[[NSNotificationCenter defaultCenter] addObserver:manager
selector:@selector(handleNetworkChange:)
name:kReachabilityChangedNotification
object:nil];
[self setReachability:[Reachability reachabilityWithHostName:@"your.host.com"]];
[self.reachability startNotifier];
现在,当网络状态发生变化时启动和停止队列:
-(void)handleNetworkChange:(NSNotification *)sender {
NetworkStatus remoteHostStatus = [self.reachability currentReachabilityStatus];
if (remoteHostStatus == NotReachable) {
[self.operationQueue setSuspended:YES];
}
else {
[self.operationQueue setSuspended:NO];
}
}
您可以使用以下命令对块进行排队:
[self.operationQueue addOperationWithBlock:^{
// do something requiring network access
}];
暂停队列只会阻止操作启动——它不会暂停正在进行的操作。在执行操作时,您总是有可能会丢失网络,因此您应该在操作中考虑到这一点。