gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:24:31 25 4
gpt4 key购买 nike

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

//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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com