我有以下代码将用户草图数据保存到文件中...
//Auto Save the sketch
NSString *filename = [NSString stringWithFormat:@"%@.png", sketchID];
CGImageRef imageRef = CGBitmapContextCreateImage(paintView.canvas.mBitmapContext);
UIImage* image = [[UIImage alloc] initWithCGImage:imageRef];
NSData* imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filename atomically:YES];
CGImageRelease(imageRef);
[image release];
SketchID
是一个唯一的字母数字值,因此我要保存到的文件名示例为“p1.png”。我用来读取文件的代码是...//Load the sketch where the user left off, if there is one
if(fileName != nil)
{
UIImage* image = [UIImage imageWithContentsOfFile:fileName];
if(image != nil)
{
.
.
在模拟器上运行时,此代码似乎可以正常工作,但是当我在设备上运行它时,无法加载图像。我是iOS开发的新手,我仍在学习如何存储文件。我的问题是...
writeToFile:
方法时“p1.png”可以正常工作?那imageWithContentsOfFile:
方法呢? 最佳答案
为什么保存/加载文件有效
在模拟器上,而不在设备上?
有很多原因,但是最常见的原因是试图写入设备上不可写的位置,而最常见的原因是写入应用程序捆绑包本身。
所有iPhone应用程序都在设备上被“沙盒化”,这意味着它们无法访问应用程序安装目录之外的文件系统。
当我创建所需的文件名时
要将数据保存到,我还需要
包含特定目录的路径
在iPhone上应该有数据的地方
妥善存放?还是应该“p1.png”
当我调用writeToFile时,工作正常:
方法?那呢
imageWithContentsOfFile:方法?
您可以写入应用程序的temp目录(如果只需要在运行过程中临时放置一些东西)或Documents目录(如果需要更永久地存储某些东西,并通过iTunes进行备份)。
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];