0

我正在我的 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 的 PFObjects 并将它们存储在本地。

我想我真的不明白文件 URL 是如何运作的。

谢谢你。

4

2 回答 2

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 不会停滞不前,因为一旦调度此队列,它将返回并继续评估应用程序的其余部分。

于 2015-11-25T19:29:54.397 回答
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];
            });
        });
于 2015-11-26T07:07:52.710 回答