下面的代碼是爲了更好的理解[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;
}
是否有'main'持續足夠長的時間來輸入一個完成塊',或者'main'總是在其中一個'blocks'開始之前終止。 – Idr
您需要一個運行循環。見http://stackoverflow.com/questions/2154600/run-nsrunloop-in-a-cocoa-command-line-program – matt