加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 为什么我的数据成功写入iPhone模拟器上的文件,而

发布时间:2020-12-16 09:29:26 所属栏目:百科 来源:网络整理
导读:我有以下代码将用户草图数据保存到文件中… //Auto Save the sketchNSString *filename = [NSString stringWithFormat:@"%@.png",sketchID];CGImageRef imageRef = CGBitmapContextCreateImage(paintView.canvas.mBitmapContext);UIImage* image = [[UIImage
我有以下代码将用户草图数据保存到文件中…

//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开发的新手,我还在学习如何存储文件.我的问题是……

>为什么保存/加载文件在模拟器上工作,而不是设备?
>当我创建我想要保存数据的文件名时,是否还需要在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];

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读