我在viewdidload方法中创建了一堆图像。图像来自PFFile来自解析,因此它们包含我的图像数据的fileURL。
我的问题是这两行代码大大减慢了我的应用程序并破坏了我的用户体验:
//get scene object
PFObject *sceneObject = self.scenes[i];
//get the PFFile and filetype
PFFile *file = [sceneObject objectForKey:@"file"];
NSString *fileType = [sceneObject objectForKey:@"fileType"];
//check the filetype
if ([fileType isEqual: @"image"])
{
//get image
NSURL *imageFileUrl = [[NSURL alloc] initWithString:file.url];
NSData *imageData = [NSData dataWithContentsOfURL:imageFileUrl]; ********** these
imageView.image = [UIImage imageWithData:imageData]; ********************* lines
}
如何更快地获取此图像/这些图像(这是嵌套在for循环中)?我已经下载了包含PFFiles的PFObject并将其存储在本地。
我想我真的不明白文件网址是如何运作的。
谢谢。
答案 0 :(得分:2)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSURL *imageFileUrl = [[NSURL alloc] initWithString:file.url];
NSData *imageData = [NSData dataWithContentsOfURL:imageFileUrl];
dispatch_get_main_queue(), ^{
imageView.image = [UIImage imageWithData:imageData];
});
});
尚未测试,但这是要点。从主队列中获取文件加载并使其异步。 UI不会陷入困境,因为只要调度此队列,它就会返回并继续评估应用程序的其余部分。
答案 1 :(得分:0)
我正在使用像这样的东西:
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[imageFrame addSubview:activityIndicator];
activityIndicator.center = CGPointMake(imageFrame.frame.size.width / 2, imageFrame.frame.size.height / 2);
[activityIndicator startAnimating];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:thumb]];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = [UIImage imageWithData:imageData];
img.image = image;
[imageOver addSubview:img];
[activityIndicator removeFromSuperview];
});
});