如何知道UIimageView何时完成加载?

时间:2011-02-27 11:32:00

标签: iphone objective-c uikit uiimageview

在我的视图控制器中,如何知道某个UIImageView何时完成加载(来自文档目录的大型jpeg)?我需要知道,以便我可以将占位符低分辨率图像视图与此高分辨率图像视图交换。我是否需要创建自定义回调才能知道这一点?无论如何都没关系。

顺便说一下,这里是我加载图片的代码片段:

NSString *fileName = [NSString stringWithFormat:@"hires_%i.jpg", currentPage];
NSString *filePath = [NSString stringWithFormat:@"%@/BookImage/%@", [self documentsDirectory], fileName];
hiResImageView.image = [[[UIImage alloc] initWithContentsOfFile:filePath] autorelease];

1 个答案:

答案 0 :(得分:2)

UIImageView根本没有进行任何加载。所有加载都由[[UIImage alloc] initWithContentsOfFile:filePath]完成,并且在加载文件时阻塞了您的线程(因此在调用最终返回时加载已经完成)。

你想要做的是这样的事情:

- (void)loadImage:(NSString *)filePath {
    [self performSelectorInBackground:@selector(loadImageInBackground:) withObject:filePath];
}

- (void)loadImageInBackground:(NSString *)filePath {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
    [self performSelectorOnMainThread:@selector(didLoadImageInBackground:) withObject:image waitUntilDone:YES];
    [image release];
    [pool release];
}

- (void)didLoadImageInBackground:(UIImage *)image {
    self.imageView.image = image;
}

您需要设置self.imageView以显示低分辨率图像,然后调用loadImage:加载高分辨率版本。

请注意,如果在从早期调用调用didLoadImageInBackground:之前重复调用此方法,则可能导致设备内存不足。或者你可能让第一次调用的图像加载的时间比第二次调用的第二次调用的第二次调用的图像要长,然后才调用第一次调用。修复这些问题留给读者练习(或另一个问题)。

相关问题