我有一个包含用户数据的信息词典。目前,它被写入与app相同的目录中的xml文件。但是,我很确定cocoa允许我将这个xml文件写入应用程序包或应用程序中的一些Resources目录。
有人可以教我怎么做吗?
答案 0 :(得分:1)
您希望将NSFileManager
createFileAtPath:contents:attributes:
NSDocumentDirectory
{相对于您的捆绑包/Documents
NSData
与您的xml文件的NSString *myFileName = @"SOMEFILE.xml";
NSFileManager *fileManager = [NSFileManager defaultManager];
// This will give the absolute path of the Documents directory for your App
NSString *docsDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// This will join the Documents directory path and the file name to make a single absolute path (exactly like os.path.join, if you python)
NSString *xmlWritePath = [docsDirPath stringByAppendingPathComponent:myFileName];
// Replace this next line with something to turn your XML into an NSData
NSData *xmlData = [[NSData alloc] initWithContentsOfURL:@"http://someurl.com/mydoc.xml"];
// Write the file at xmlWritePath and put xmlData in the file.
BOOL created = [fileManager createFileAtPath:xmlWritePath contents:xmlData attributes:nil];
if (created) {
NSLog(@"File created successfully!");
} else {
NSLog(@"File creation FAILED!");
}
// Only necessary if you are NOT using ARC and you alloc'd the NSData above:
[xmlData release], xmlData = nil;
一起使用。
像这样:
NSUserDefaults
一些参考文献:
NSFileManager
Reference Docs
NSData
Reference Docs
修改强>
在回复您的评论时,这将是// Some data that you would want to replace with your own XML / Dict / Array / etc
NSMutableDictionary *nodeDict1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"object1", @"key1", nil];
NSMutableDictionary *nodeDict2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"object2", @"key2", nil];
NSArray *nodes = [NSArray arrayWithObjects:nodeDict1, nodeDict2, nil];
// Save the object in standardUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:nodes forKey:@"XMLNODELIST"];
[[NSUserDefaults standardUserDefaults] synchronize];
在App运行之间保存可序列化数据的典型用法:
NSArray *xmlNodeList = [[NSUserDefaults standardUserDefaults] arrayForKey:@"XMLNODELIST"];
要检索已保存的值(下次启动应用程序,或从应用程序的其他部分等):
{{1}}