我已經創建了NSOperation
類,我叫NSURLConnection
獲取一些數據。 我打電話NSURLConnection
使用NSOperation
類中的主線程。 NSURLConnection
的代表設置爲NSOperation
類對象。 來自NSURLConnection
的呼叫出現在主線程中。 我需要使用相同的操作線程處理這些數據。我如何實現這一目標?NSOperation + NSURLConnection
@implementation ModelCreationSearchOperation {
int try;
}
- (BOOL)isConcurrent
{
return YES;
}
- (void)start
{
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"];
dispatch_async(dispatch_get_main_queue(), ^{
if (self.isCancelled) {
[self finish];
return;
}
});
[self fetchData];
}
-(void)fetchData {
dispatch_async(dispatch_get_main_queue(), ^{
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
});
}
- (void)finish
{
[self willChangeValueForKey:@"isExecuting"];
[self willChangeValueForKey:@"isFinished"];
_isExecuting = NO;
_isFinished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
[self cancel];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//Main thread
//Want to perform parsing of response data on operation thread ....
}
說明順便說一句,與您的問題無關,'isCancelled'邏輯不太正確。在設置'isExecuting'並調用'fetchData'之前,你應該檢查一下。將它分派到主隊列是沒有意義的(也是適得其反的,因爲你的'return'應該阻止獲取的發生,但是現在你只是從調度中返回,而'isExecuting'和' fetchData'正在發生,無論op是否被取消,這不是你想要的,我敢肯定)。另外,從iOS 7開始,你也應該實現'isAsynchronous'。 – Rob
哦,是的......很棒的......感謝...... –