我想獲得以下內容:我在NSOperationQueue中有兩個NSOperations。首先是從網站下載(獲取一些json數據),下一個是解析該數據。這是依賴性操作。 我不明白如何將它們連接在一起。如果它們都被分配並且在隊列中,那麼如何將json字符串轉換爲解析它的操作?如果這個隊列在另一個NSOperationQueue內執行一個由前面提到的兩個NSOperation組成的NSOperation,那麼這是一個問題嗎?NSOperation之間的數據傳輸
我能找到的所有數據都是傳遞給主線程(performSelectorOnMainThread)上的委託,但我需要在後臺執行所有這些操作。
謝謝。 代碼: NSDownload:的NSOperation
- (instancetype)initWithURLString:(NSString *)urlString andDelegate:(id<JSONDataDelegate>)delegate
{
self = [super init];
if (self) {
_urlStr = urlString;
_delegate = delegate; /// this needs to be a NSOPeration
_receivedData = [NSMutableData dataWithCapacity:256];
}
return self;
}
#pragma mark - OVERRIDE
- (void)main
{
@autoreleasepool {
if (self.isCancelled) {
return;
}
NSURL *url = [NSURL URLWithString:self.urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
}
#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (self.isCancelled) {
[connection cancel];
self.receivedData = nil;
return;
}
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (self.isCancelled) {
self.receivedData = nil;
return;
}
// return data to the delegate
NSDictionary *responseDict = @{JSON_REQUESTED_URL : self.urlStr,
JSON_RECEIVED_RESPONSE : self.receivedData};
[(NSObject *)self.delegate performSelectorOnMainThread:@selector(didReceiveJSONResponse:) withObject:responseDict waitUntilDone:NO]; // ok to uses performSelector as this data is not for use on the main thread ???
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// return error to the delegate
[(NSObject *)self.delegate performSelectorOnMainThread:@selector(didFailToReceiveDataWithError:) withObject:error waitUntilDone:NO];
}
你真的需要同時創建兩個'NSOperations'嗎?你能不能創建'DownloadOperation'並將其添加到隊列中,並在完成後創建'ParseOperation'並將其添加到隊列中? – lucianomarisi
這將是可能的。但是,NSOperations之間的依賴關係是什麼?他們不應該是一個管道? – user1028028
您的應用程序的體系結構真的取決於您,但您可以讓'DownloadOperation'將數據保存在局部變量中(在「NSOperations」的範圍內並將「ParseOperation」添加爲將使用此變量的依賴項。或者在'DownloadOperation'的完成塊中,您可以將下載的數據設置到'ParseOperation',所以當'ParseOperation'開始時數據就在那裏。也許發佈當前的代碼來討論什麼是最合適的解決方案。 – lucianomarisi