Ios iPhone UIImage-数据持久性
关于应用程序会话之间数据持久性的简单问题 我的应用程序允许用户使用UIImagePickerController从库中选择图像。然后将选定的照片用作应用程序的背景 由于UIImagePickerController委托方法实际上返回的是图像,而不是图像路径,我想知道在用户会话中保存此图像的最佳方法是什么 目前我不需要保存任何其他数据,因为其他所有数据都是从SQL Server中提取的,但我不希望增加必须将映像存储在服务器中的额外开销,这意味着每次用户打开应用程序时,首先必须将背景图像从服务器下载到字节数组中,然后转换为图像 我发现以下代码可以保存图像:Ios iPhone UIImage-数据持久性,ios,objective-c,iphone,uiimage,persistence,Ios,Objective C,Iphone,Uiimage,Persistence,关于应用程序会话之间数据持久性的简单问题 我的应用程序允许用户使用UIImagePickerController从库中选择图像。然后将选定的照片用作应用程序的背景 由于UIImagePickerController委托方法实际上返回的是图像,而不是图像路径,我想知道在用户会话中保存此图像的最佳方法是什么 目前我不需要保存任何其他数据,因为其他所有数据都是从SQL Server中提取的,但我不希望增加必须将映像存储在服务器中的额外开销,这意味着每次用户打开应用程序时,首先必须将背景图像从服务器下载
- (void)saveImage:(UIImage *)image withName:(NSString *)name {
//save image
NSData *data = UIImageJPEGRepresentation(image, 1.0);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
[fileManager createFileAtPath:fullPath contents:data attributes:nil];
}
我目前不在mac电脑上,因此无法测试此代码,但我对上述代码有几个问题:
我不希望文件系统中有太多的文件。所以我想要一个单一的背景文件(background.png);上面的代码如何处理这个文件已经存在的情况
它会覆盖现有文件还是抛出错误
如何再次加载图像?您必须先删除文件:
- (void)saveImage:(UIImage *)image withName:(NSString *)name {
//save image
NSData *data = UIImageJPEGRepresentation(image, 1.0);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
NSError *error = nil;
if( [fileManager fileExistsAtPath:fullPath] ){
if( ! [fileManager removeItemAtPath:fullPath error:&error] ) {
NSLog(@"Failed deleting background image file %@", error);
// the write below should fail. Add your own flag and check below.
}
}
[data writeToFile:fullPath atomically:YES];
}
读回应按如下方式进行:
...
UIImage *bgImage = [UIImage imageWithContentsOfFile:fullPath];
...