我有一个包含用户数据的信息字典。目前,它被写入与应用程序相同目录中的 xml 文件。但是,我很确定 cocoa 允许我将此 xml 文件写入应用程序包或应用程序内的某个资源目录中。
有人可以教我如何做到这一点吗?
我有一个包含用户数据的信息字典。目前,它被写入与应用程序相同目录中的 xml 文件。但是,我很确定 cocoa 允许我将此 xml 文件写入应用程序包或应用程序内的某个资源目录中。
有人可以教我如何做到这一点吗?
您可能希望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
在 App 运行之间保存可序列化数据的典型用法:
// 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];
要检索保存的值(下次启动应用程序时,或从应用程序的另一部分等):
NSArray *xmlNodeList = [[NSUserDefaults standardUserDefaults] arrayForKey:@"XMLNODELIST"];