writeToFile在iphone上失败但在模拟器上运行 [英] writeToFile fails on iphone but works on simulator

查看:105
本文介绍了writeToFile在iphone上失败但在模拟器上运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NSString *myfile = [[NSBundle] mainBundle] pathForResource:@"fileName" ofType:@"plist"];    
NSMutableArray *mydata= [[NSMutableArray alloc] initWithContentsOfFile:myfile];

/* code to modify mydata */

[mydata writeToFile:myfile atomically:YES]

如果模拟器'fileName.plist'被修改但是在iphone设备文件保持不变的情况下。也没有例外。

In case of simulator 'fileName.plist' is modified but in case of iphone device file remains unchanged. There is no exception seen either.

上述代码是否可以在iphone和模拟器上正常工作?

Is the above code expected to work fine on both iphone and simulator ?

当我将鼠标悬停在'mydata'上时,我也会在调试器中看到模拟器和设备的不同值。在模拟器的情况下,我看到例如'5个对象'但是在实际设备的情况下它显示'{(int)[$ VAR count]}'。这可能与未写入的文件有关吗?

Also in the debugger when I hover over 'mydata' I see different values in case of simulator and device. In case of simulator I see for example, '5 objects' but in case of actual device it shows '{(int)[$VAR count]}'. Could this be related to file not being written ?

推荐答案

您无法写入软件包资源目录中的文件。最重要的是,您不希望这样做,因为更新应用程序时将覆盖任何更改。文档目录在各个版本中都存在,并且(我相信)它通过itunes进行备份。

You can't write to files in a bundle's resource directory. On top of that you wouldn't want to, because any changes would be overwritten when you update your app. The documents directory persists across versions and (I believe) it is backed up via itunes.

这是一个片段,用于检查文档目录中的plist。如果该文件不存在,则将资源中的plist复制到文档目录中。

Here is a snippet that checks the documents directory for a plist. if the file doesn't exist it copies a plist out of the resources into the documents directory.

BOOL success;
NSFileManager* fileManager = [NSFileManager defaultManager]; 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"score.plist"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return success;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"score.plist"]];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
return success;

这篇关于writeToFile在iphone上失败但在模拟器上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆