Objective c 如何在应用程序本身中存储cocoa应用程序的关键值数据?

Objective c 如何在应用程序本身中存储cocoa应用程序的关键值数据?,objective-c,cocoa,dictionary,nsbundle,key-value-store,Objective C,Cocoa,Dictionary,Nsbundle,Key Value Store,我有一个包含用户数据的信息字典。目前,它被写入与应用程序位于同一目录中的xml文件中。但是,我非常确定cocoa允许我将此xml文件写入应用程序包或应用程序中的某个资源目录 有人能教我怎么做吗?您想使用NSFileManager在NSDocumentDirectory中创建文件路径:内容:属性:(相对于您的包,这是/Documents)和xml文件的NSData。 大概是这样的: NSString *myFileName = @"SOMEFILE.xml"; NSFileManager *fil

我有一个包含用户数据的信息字典。目前,它被写入与应用程序位于同一目录中的xml文件中。但是,我非常确定cocoa允许我将此xml文件写入应用程序包或应用程序中的某个资源目录


有人能教我怎么做吗?

您想使用
NSFileManager
NSDocumentDirectory
中创建文件路径:内容:属性:(相对于您的包,这是
/Documents
)和xml文件的
NSData

大概是这样的:

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
在应用程序运行之间保存可序列化数据的典型用法:

// 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];
要检索保存的值(下次启动应用程序时,或从应用程序的另一部分等),请执行以下操作:


NSDocumentDirectory保存在iCloud中。小心不要将大文件放入,苹果会警告你……有没有办法不将我的xml文件存储在我的应用程序之外?我可以将它存储在我的应用程序中的资源包中吗?@dragoncharmer当然可以,这就是
NSUserDefaults
的用途。我来举个例子。@dragoncharmer Np,很乐意帮忙。@dragoncharmer:你可以在构建时将文件放入你的应用程序中,但你不能依赖你的应用程序包在用户的机器上是可写的。您需要的可能是应用程序支持文件夹。
NSArray *xmlNodeList = [[NSUserDefaults standardUserDefaults] arrayForKey:@"XMLNODELIST"];