【发布时间】:2015-06-14 03:25:50
【问题描述】:
以下代码是为了让我更好地理解[NSURLConnection sendAsynchronousRequest:queue:completionHandler]。
completionHandler 块中有 NSLog 语句,但是当我从命令行项目的 XCode 中的 main.m 中运行它时,它永远不会进入 completionHandler 块。我尝试过使用不同的队列,mainQueue 和 currentQueue,但都不起作用。
我的预感是队列在请求完成之前就被释放了,并且涉及保留周期。
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSCache *myCache = [[NSCache alloc] init];
NSArray *images = @[
@"http://i.stack.imgur.com/E66qr.png",
@"http://www.tiempoyquimera.com/wp-content/uploads/2010/01/Euro-Trash-Girl-2010.jpg",
@"http://1.bp.blogspot.com/-Mxd8AB2nbQY/UYCISJiQz3I/AAAAAAAAAH8/Tc43U8aa9dM/s1600/Tarantino10colhans_1460858i.jpg",
@"https://awestruckwanderer.files.wordpress.com/2014/02/alan-watts.png",
@"http://www.esalen.org/sites/default/files/photo_images/20120201_DELLIS__MG_9612_711.jpg"];
for (NSString *image in images){
NSURL *myURL = [NSURL URLWithString:image];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:myURL];
NSLog(@"Can handle request %@", @([NSURLConnection canHandleRequest:request]));
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(@"In the completion handler");
if (!error)
{
// save data to cache with url as key
NSLog(@"Image Added to Cache");
[myCache setObject:data
forKey:myURL];
} else
{
NSLog(@"Image Not Added to Cache");
}
}];
}
}
return 0;
}
【问题讨论】:
标签: ios objective-c arrays asynchronous