【发布时间】:2015-07-08 15:09:31
【问题描述】:
我使用这种方法来存储图像,据我了解,这种方法可以持久地存储数据。问题是当我重新启动模拟器时,图像已经消失/无法加载。 无论如何,这是代码:
- (NSString *)saveImage:(NSMutableString*)account{
NSString *dir=[NSString stringWithFormat:@"http://example.com"];
NSURL *url=[NSURL URLWithString:dir];
NSData *imageData = UIImagePNGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:url]]);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *imageName = [NSString stringWithFormat:@"%@%@", account,@"Banner.png"];
NSString *imagePath = [documentDirectory stringByAppendingFormat:imageName];
NSLog((@"pre writing to file"));
NSError *writeError = nil;
if(![imageData writeToFile:imagePath options:NSDataWritingAtomic error:&writeError]){
NSLog(@"%@: Error saving image: %@",[self class], [writeError localizedDescription]);
}
else{
NSLog(@"the cachedImagePath is %@", imagePath);
return imagePath;
}
return NULL;
}
这是用于加载图像的方法:
[UIImage imageWithContentsOfFile:bannerPath]
bannerPath 是保存在 NSUserDefaults 中的保存方法返回的 imagePath。
我做错了吗?我该如何解决? 谢谢。
编辑:我用以下方法检查文件是否存在:
[[NSFileManager defaultManager] fileExistsAtPath:bannerPath];
我返回 false。
【问题讨论】:
-
“重启模拟器”是什么意思?以及如何保存 imagePath?
-
我在 iPhone 6 的模拟器中运行该应用程序,该模拟器包含在 Xcode 中,我的意思是我关闭模拟器并再次运行该应用程序。我将 imagePath 保存在 NSUserDefaults 中。
标签: ios image storage nsuserdefaults