私はあなたが使用しようとしていることを正確に行います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
}];
キューを一時停止すると、操作の開始が妨げられるだけです。進行中の操作は一時停止されません。操作の実行中にネットワークが失われる可能性は常にあるため、操作ではそのことを考慮する必要があります。