我有一个应用程序可以下载几张图像并将它们存储在手机上。总共可能需要大约 20 张图片。我需要能够根据用户所在的屏幕随意检索这些图像中的任何一个。这些图像将无限期地存储,所以我不想使用临时目录。
目前我有一个名为 Images 的类,其中包含这些方法
- (void) cacheImage: (NSString *) ImageURLString : (NSString *)imageName
{
NSURL *ImageURL = [NSURL URLWithString: ImageURLString];
// Generate a unique path to a resource representing the image you want
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex: 0];
NSString *docFile = [docDir stringByAppendingPathComponent: imageName];
// Check for file existence
if(![[NSFileManager defaultManager] fileExistsAtPath: docFile])
{
// The file doesn't exist, we should get a copy of it
// Fetch image
NSData *data = [[NSData alloc] initWithContentsOfURL: ImageURL];
UIImage *image = [[UIImage alloc] initWithData: data];
// Is it PNG or JPG/JPEG?
// Running the image representation function writes the data from the image to a file
if([ImageURLString rangeOfString: @".png" options: NSCaseInsensitiveSearch].location != NSNotFound)
{
[UIImagePNGRepresentation(image) writeToFile: docFile atomically: YES];
}
else if([ImageURLString rangeOfString: @".jpg" options: NSCaseInsensitiveSearch].location != NSNotFound ||
[ImageURLString rangeOfString: @".jpeg" options: NSCaseInsensitiveSearch].location != NSNotFound)
{
[UIImageJPEGRepresentation(image, 100) writeToFile: docFile atomically: YES];
}
}
}
- (UIImage *) getCachedImage : (NSString *)imageName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* cachedPath = [documentsDirectory stringByAppendingPathComponent:imageName];
UIImage *image;
// Check for a cached version
if([[NSFileManager defaultManager] fileExistsAtPath: cachedPath])
{
image = [UIImage imageWithContentsOfFile: cachedPath]; // this is the cached image
}
else
{
NSLog(@"Error getting image %@", imageName);
}
return image;
}
-(void)getImages
{
//example
NSString *image1URL = @"http://test/image1.png";
NSString *image2URL = @"http://test/image2.png";
NSString *image3URL = @"http://test/image3.png";
[self cacheImage:sLogo: @"Image1"];
[self cacheImage:sBlankNav: @"Image2"];
[self cacheImage:buttonLarge :@"Image3"];
}
-(void) storeImages
{
image1 = [self getCachedImage:@"Image1"];
image2 = [self getCachedImage:@"Image2"];
image3 = [self getCachedImage:@"Image3"];
}
所以我使用这样的代码
Images *cache = [[Images alloc]init];
[cache storeImages];
get images 方法在应用程序第一次开始获取图像时调用一次,之后不会再次调用,除非服务器上的图像已更新并且我需要检索更新的图像。
该代码有效,但问题是当我导航到使用它的屏幕时,在加载图像时屏幕加载之前有一个非常轻微的延迟。
我的应用程序是一个选项卡式应用程序,所以它从选项卡 1 开始,我单击实现代码的选项卡 2,第一次加载时会有轻微的暂停。它不会持续很长时间,但它很明显并且很烦人。之后就很好了,因为它已经加载了。但是对于导航控制器,每次从第一个 VC 移动到第二个 VC 时,都会再次调用该方法,因此每次导航时都会出现延迟。
图片不是很大,最大的是68kb,其他的都小很多。目前我只是用 5 张图片进行测试。有没有更有效的方法来存储和检索图像,还是我的代码有问题?我需要能够在没有任何明显延迟的情况下检索这些图像,以使我的应用程序保持流畅而不生涩或笨拙。
提前致谢!!