代码之家  ›  专栏  ›  技术社区  ›  Prashant Cholachagudda

从文件异步加载图像

  •  3
  • Prashant Cholachagudda  · 技术社区  · 15 年前

    我在本地存储器中有一个相对的图像,我想在不干扰UI线程的情况下向用户显示它。 我正在使用

    [[UIImage alloc] initWithContentsOfFile:path];
    

    加载图像。

    请提供任何建议/帮助。。。。

    2 回复  |  直到 15 年前
        1
  •  5
  •   John Franklin    15 年前

    如果您要做的只是保持UI线程可用,请设置一个简短的方法将其加载到后台,并在完成后更新imageView:

    -(void)backgroundLoadImageFromPath:(NSString*)path {
        UIImage *newImage = [UIImage imageWithContentsOfFile:path];
        [myImageView performSelectorOnMainThread:@selector(setImage:) withObject:newImage waitUntilDone:YES];
    }
    

    这个假设 myImageView 是类的成员变量。现在,只需在后台从任何线程运行它:

    [self performSelectorInBackground:@selector(backgroundLoadImageFromPath:) withObject:path];
    

    注意,在 backgroundLoadImageFromPath setImage: 选择器完成,否则后台线程的自动释放池可能会在 设置图像:

        2
  •  0
  •   Igor    13 年前

    您可以为此目的使用NSInvocationOperation: 呼叫

    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                        initWithTarget:self
                                        selector:@selector(loadImage:)
                                        object:imagePath];
    [queue addOperation:operation];
    

    哪里:

    - (void)loadImage:(NSString *)path
    
    {
    
    NSData* imageFileData = [[NSData alloc] initWithContentsOfFile:path];
     UIImage* image = [[UIImage alloc] initWithData:imageFileData];
    
    [self performSelectorOnMainThread:@selector(displayImage:) withObject:image waitUntilDone:NO];
    }
    
    - (void)displayImage:(UIImage *)image
    {
        [imageView setImage:image]; //UIImageView
    }