要下载一堆Twitter时间轴,我在循环中创建了TWRequest
个对象,并将它们放入NSOperationQueue
:
twitterRequestQueue = [[NSOperationQueue alloc] init];
// Get a reference to a Twitter account
NSArray *screenNames = @[@"gruber", @"kottke", @"ev", @"brad", @"borkware", @"jack", @"greatdismal", @"wilshipley"];
NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/user_timeline.json"];
for (NSString *screenName in screenNames) {
NSDictionary *parameters = @{@"screen_name" : screenName, @"count" : @"200" };
TWRequest *request = [[TWRequest alloc] initWithURL:url parameters:parameters requestMethod:TWRequestMethodGET];
[request setAccount:account];
// Make an operation using the Twitter request
NSBlockOperation *twitterOperation = [NSBlockOperation blockOperationWithBlock:^{
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
// Do stuff with the responseData
}];
}];
// Put the requests into an operation queue
[twitterRequestQueue addOperation:twitterOperation];
}
要确定何时下载了所有时间轴,我首先尝试using KVO on twitterRequestQueue
's operationCount
。在所有Twitter请求之后我也尝试了adding a dependant operation to the queue。这两个都失败了,因为Twitter请求几乎立即返回并在调用完成块之前从操作队列中删除。
相反,我将我的请求手动存储在一个可变数组中,在Twitter完成块的末尾调用自定义方法[self requestCompleted:request];
,并在每次完成时手动删除我的可变数组中的请求:
- (void)requestCompleted:(TWRequest *)request
{
NSDictionary *parameters = [request parameters];
NSString *screenName = [parameters valueForKey:@"screen_name"];
NSLog(@"Request completed: %@", screenName);
[requestsInProgress removeObject:request];
if ([requestsInProgress count] == 0) {
NSLog(@"All requests finished");
}
}
我可以使其工作的另一种方法是从Twitter请求获取signedURLRequest
并使用sendSynchronousRequest:returningResponse:error:
同步下载。
这是我的问题:
NSOperationQueue
下载这样的Twitter请求有什么意义吗?