【问题标题】:writeToFile fails on iphone but works on simulatorwriteToFile 在 iphone 上失败,但在模拟器上工作
【发布时间】:2010-01-19 08:15:30
【问题描述】:
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设备文件的情况下保持不变。也没有看到异常。

上面的代码预计在 iphone 和模拟器上都能正常工作吗?

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

【问题讨论】:

    标签: iphone


    【解决方案1】:

    您不能写入包资源目录中的文件。最重要的是,您不希望这样做,因为当您更新应用程序时,任何更改都会被覆盖。文档目录跨版本持续存在,并且(我相信)它是通过 iTunes 备份的。

    这是一个 sn-p 检查文档目录中的 plist。如果文件不存在,它会将资源中的 plist 复制到文档目录中。

    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;
    

    【讨论】:

    • 谢谢肯尼。那很有帮助。我已经使用此代码实现了我的东西,现在它也可以与设备一起使用。
    • 谢谢,成功了。我的高分遇到了这个问题(如示例;),从捆绑资源中复制它是包含一些默认分数的好主意。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 2013-05-05
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多