2010-01-19 170 views
1
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设备文件保持不变的情况下。也没有例外。writeToFile在iphone上失败,但在模拟器上工作

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

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

回答

5

您无法写入捆绑软件资源目录中的文件。最重要的是,你不想这样做,因为更新应用程序时,任何更改都会被覆盖。文档目录在各个版本中保持不变,并且(我相信)它通过iTunes进行备份。

这是一个代码片段,用于检查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; 
+0

谢谢肯尼。这很有帮助。我已经使用这个代码实现了我的东西,现在它也和设备一起工作。 – climbon 2010-01-20 07:11:46

+0

谢谢,做到了。用我的高分(比如这个例子)来解决这个问题,并且从一个包资源中复制它是包含一些默认分数的好主意。 – 2013-06-07 15:24:07

相关问题