我有一种从服务器下载一些图片的方法。我使用异步块(NSMutableArray *imgtmp)定义了下载数据的缓冲区,但还没有弄清楚如何从那里取出数组。访问 imgtmp 以返回其内容或从中设置实例变量的最佳方法是什么?
我一直在查看Apple Block 文档,但我一定不在正确的部分。我需要以某种方式使用__block
关键字声明 imgtmp 吗?我试过了,但 imgtmp 在块外仍然是空的。谢谢!
编辑:使用工作模型更新代码
- (void) loadImages
{
// temp array for downloaded images. If all downloads complete, load into the actual image data array for tablerows
__block NSMutableArray *imgtmp = [[NSMutableArray alloc] init];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0),
^{
int error = 0;
int totalitems = 0;
NSMutableArray *picbuf = [[NSMutableArray alloc] init];
for (int i=0; i < _imageURLS.count;i++)
{
NSLog(@"loading image for main image holder at index %i",i);
NSURL *mynsurl = [[NSURL alloc] initWithString:[_imageURLS objectAtIndex:i]];
NSData *imgData = [NSData dataWithContentsOfURL:mynsurl];
UIImage *img = [UIImage imageWithData:imgData];
if (img)
{
[picbuf addObject:img];
totalitems++;
}
else
{
NSLog(@"error loading img from %@", [_imageURLS objectAtIndex:i]);
error++;
}
}// for int i...
dispatch_async(dispatch_get_main_queue(),
^{
NSLog(@"_loadedImages download COMPLETE");
imgtmp = picbuf;
[_tvStatus setText: [NSString stringWithFormat:@"%d objects have been retrieved", totalitems]];
NSLog (@"imgtmp contains %u images", [imgtmp count]);
});// get_main_queue
});// get_global_queue
}