做以下事情:
- (NSString *)ImagesDirectoryPath
{
NSFileManager *fileManger = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
basePath = [basePath stringByAppendingFormat:@"/Images"];
NSError *error;
if(![fileManger fileExistsAtPath:basePath])
{
[fileManger createDirectoryAtPath:basePath withIntermediateDirectories:NO attributes:nil error:&error];
}
return basePath;
}
此方法将返回 Document Directory 下的 Your Images Path
现在你有图像名称所以我们将检查图像目录是否存在。如果退出,则使用该 img 或下载 img 然后存储它 // 此代码将是 cellForRowAtIndexPath
NSString *strImgPath = [self ImagesDirectoryPath];
strImgPath = [strImgPath stringByAppendingFormat:[NSString stringWithFormat:@"/%@.png",imgName]];
NSFileManager *fileManger = [NSFileManager defaultManager];
if(![fileManger fileExistsAtPath:strImgPath]) //Check wether image exits at Image Folder in Doc Dir
{//file not exists
UIImage *imgForCell = [MyClass getImageWithName:imgName];
if(imgForCell)
{
NSData *dataImg = UIImagePNGRepresentation(imgForCell);
if(dataImg)
{
[dataImg writeToFile:strImgPath atomically:YES];
}
}
imgView.image=imgForCell; //Set Image in ImageView
}
else
{//file exists
NSData *imgData = [NSData dataWithContentsOfFile:strImgPath];
UIImage*imgFound = [UIImage imageWithData:imgData];
imgView.image=imgFound; //Set Image in ImageView
}