2009-08-16 92 views
3

我似乎已经在关于从字符串保存xml文件的问题上发生了一些问题(这是在iPhone上完成的) 文件本身存在并包含在项目中因此在工作区内),以及我从代码片段中得到的所有指示在模拟器上没有任何错误并且在iPhone上失败(错误513),但是在任何情况下都不保存文件!在Objective-C(iPhone)中将字符串保存到文件中

{ 
Hits = config->Hits; 

NSString* filenameStr = [m_FileName stringByAppendingFormat: @".xml" ]; 
NSString* pData = [self getDataString]; // write xml format - checked out ok 
NSError  *error; 

/* option 2 - does not work as well 
NSBundle  *mainBundle = [NSBundle mainBundle]; 
NSURL   *xmlURL = [NSURL fileURLWithPath:[mainBundle pathForResource: m_FileName ofType: @"xml"]]; 

if(![pData writeToURL: xmlURL atomically: true encoding:NSUTF8StringEncoding error:&error]) 
{ 
NSLog(@"Houston - we have a problem %[email protected]\n",[error localizedFailureReason]); 
return false; 
} 
*/ 

if(![pData writeToFile: filenameStr atomically: FALSE encoding:NSUTF8StringEncoding error:&error]) 
{ 
    NSLog(@"Houston - we have a problem %[email protected]\n",[error localizedFailureReason]); 
    return false; 
} 
return true; 

}

任何帮助,将不胜感激, -A

+1

你可以给字符串解释什么是错误513? 另外,注意:在打印localizedFailureReason时,最好在NSLog语句中使用%@而不是%s。 %@格式说明符需要一个NSString *,而%s需要一个以null结尾的char *字符串。 – Tyler 2009-08-16 09:24:31

+1

从技术上讲,%@使用任何NSObject类型,并调用字符串本身就是其自身的[object description];但它也适用于其他NSObject类型(例如数组,集合等) – AlBlue 2009-08-16 11:17:27

回答

19

你不应该写入文件中包含的应用程序包。在真实的iPhone上,可能会阻止您这样做,因为这些文件是数字签名的。

即使您可以修改打包文件,它也不是一个存储数据的好地方。从App Store升级或Xcode版本重新安装应用程序将覆盖原始文件。

而是将您的XML存储到Documents目录中。你可以得到这样的路径:

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
    NSUserDomainMask, YES); 
NSString* documentsDirectory = [paths objectAtIndex:0];  
NSString* leafname = [m_FileName stringByAppendingFormat: @".xml" ]; 
NSString* filenameStr = [documentsDirectory 
    stringByAppendingPathComponent:leafname]; 

如果你的文件需要你不想在你的代码生成一些初始状态,有您的应用程序检查它是否存在于文件目录中的第一次是必要的,如果缺少,请从包中的模板复制它。

存储结构化数据的替代方法是使用用户默认值。例如:

[[NSUserDefaults standardUserDefaults] setObject:foo forKey:FOO_KEY]; 
+1

+1用于用户默认方法。 但是,该文件不会防止覆盖,因为它是数字签名的,而是它是只读的,不能被覆盖。它们也是数字签名的,但这并不妨碍它被写入。 – AlBlue 2009-08-16 11:18:14

相关问题