objective-c - 为什么我的数据可以成功写入 iPhone 模拟器上的文件,而不是我的设备?

标签 objective-c ios cocoa-touch

我有以下代码将用户草图数据保存到文件中......

//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 开发的新手,我仍在学习文件的存储方式。我的问题是...

  1. 为什么保存/加载文件可以在模拟器上运行,但不能在设备上运行?
  2. 当我创建要将数据保存到的文件名时,是否还需要包含指向 iPhone 上应正确存储数据的特定目录的路径?或者当我调用 writeToFile: 方法时,“p1.png”应该工作正常吗? imageWithContentsOfFile: 方法呢?

最佳答案

Why would saving/loading the file work on the simulator, but not the device?

有很多原因,但最常见的是尝试写入设备上不可写的位置,而最常见的原因是写入应用程序包本身。

所有 iPhone 应用程序都在设备上“沙盒化”,这意味着它们无法访问应用程序安装目录之外的文件系统。

When I create the filename that I want to save the data to, do I need to also include a path to a specific directory on the iPhone where the data should be properly stored? Or should "p1.png" work fine when I call the writeToFile: method? And what about the imageWithContentsOfFile: method?

您可以写入应用程序的临时目录(如果您只需要在运行期间临时放置一些东西)或 Documents 目录(如果您需要更永久地存储一些东西,并且还需要 iTunes 对其进行备份)。

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];

关于objective-c - 为什么我的数据可以成功写入 iPhone 模拟器上的文件,而不是我的设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3532998/

相关文章:

xcode - "UIViewController subclass"没有出现在 xcode 4.3 的文件模板库中

iOS - [Fabric firebaseMode] : unrecognized selector sent to instance

ios - NSCalendarUnitEra多长时间?

ios - Swift 如何用新颜色填充叠加层

ios - 为什么在使用 prepareToRecord 时出现 AudioConverterNew 错误?

iphone - 如何确定 View Controller

ios - 从 Project 导入时,Xcode Image Assets Catalog 无法看到所有图像?

ios - NSTimeInterval 并查看日期是否超过一个小时

objective-c - 如何创建指向结构的指针并对其进行类型转换?

ios - 当 View Controller 向后导航到时重新加载表