正确的方式保存和加载图片

我正在制作一个小应用程序,用户可以在其中创build游戏configuration文件,input一些数据和可以用相机拍摄的照片。

我在NSUserDefaults的帮助下保存了大部分configuration文件数据,但是一个朋友不鼓励我将configuration文件保存在NSUserDefault

什么是在我的应用程序本地保存和检索图像的正确方法?

您应该将其保存在DocumentsCache文件夹中。 这是如何做到这一点。

保存Documents文件夹中:

 NSString* path = [NSHomeDirectory() stringByAppendingString:@"/Documents/myImage.png"]; BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil]; if (!ok) { NSLog(@"Error creating file %@", path); } else { NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path]; [myFileHandle writeData:UIImagePNGRepresentation(yourImage)]; [myFileHandle closeFile]; } 

Documents文件夹加载

 NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:path]; UIImage* loadedImage = [UIImage imageWithData:[myFileHandle readDataToEndOfFile]]; 

您也可以使用UIImageJPEGRepresentation将您的UIImage保存为JPEG文件。 更重要的是,如果您想将其保存在Cache目录中,请使用:

 [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/"] 

一种方法是使用应用程序的文档目录。 这是特定于应用程序,并不会被其他应用程序看到。
如何创build这个:
只需在App Delegate中添加一个静态函数,然后在需要path的地方使用该函数。

 - (NSString )applicationDocumentDirectory { / Returns the path to the application's documents directory. */ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; return basePath; } 

希望它帮助..

我认为这个(“iphone用户默认和uiimages”)post解决您的问题。 不要将blob保存到属性列表,例如NSUserDefaults。 在你的情况下,我会直接写入磁盘。