一次加载一个图像

所以这个代码基本上从服务器获取数据,创build一个图像,然后将其添加到视图。

不过,我希望一次更新一个视图。

现在,所有图像加载完毕后,所有的图像都立即更新。

我想更新视图,每次上传一个新的图像 – 这应该发生在addImage方法中,而是等待所有的图像加载。

我试着用dispatch_async来解决这个问题,但是没有成功。

那么我怎样一次加载一张图片?

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { //some code not displayed here that parses the JSON for (NSDictionary *image in images){ if ([[image objectForKey:@"ContentType"] isEqualToString:@"image/png"]){ NSString *imgLink = [[image objectForKey:@"MediaUrl"] JSONStringWithOptions:JKSerializeOptionPretty includeQuotes:NO error:nil]; NSURL *url = [NSURL URLWithString:path]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *img = [[UIImage alloc] initWithData:data cache:NO] dispatch_async(dispatch_get_main_queue(), ^{ [self addImage:img]; //This method adds the image to the view }); } } } 

更新:这不是一个tableview,图像作为子视图添加到UIView

我相信你正在寻找一种延迟加载的forms。 试试这个例子: Apple Lazy Loading例子

 [NSData dataWithContentsOfURL:url]; 

是一个同步操作,所以你必须等待每个图像一个接一个,基于url的图片的适当的延迟加载实现是最好的解决scheme,在此期间,你可以尝试做这样的事情

 AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { //some code not displayed here that parses the JSON for (NSDictionary *image in images){ if ([[image objectForKey:@"ContentType"] isEqualToString:@"image/png"]){ NSString *imgLink = [[image objectForKey:@"MediaUrl"] JSONStringWithOptions:JKSerializeOptionPretty includeQuotes:NO error:nil]; NSURL *url = [NSURL URLWithString:path]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *img = [[UIImage alloc] initWithData:data cache:NO] dispatch_async(dispatch_get_main_queue(), ^{ [self addImage:img]; //This method adds the image to the view }); }) } } } 

如果你想使用这个解决scheme,build议你创build你自己的并发队列,而不是使用global_queue