gpt4 book ai didi

objective-c - 如何在应用程序本身内存储 cocoa 应用程序的键值数据?

转载 作者:行者123 更新时间:2023-12-03 16:43:42 25 4
gpt4 key购买 nike

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

有人可以教我怎么做吗?

最佳答案

您需要使用 NSFileManagerNSDocumentDirectorycreateFileAtPath:contents:attributes: (相对于您的包,这是 /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;

一些引用:

NSFileManager Reference Docs
NSData Reference Docs

<小时/>

编辑

根据您的评论,这将是 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];

要检索保存的值(下次启动应用程序时,或从应用程序的其他部分等):

NSArray *xmlNodeList = [[NSUserDefaults standardUserDefaults] arrayForKey:@"XMLNODELIST"];

NSUserDefaults Reference Docs

关于objective-c - 如何在应用程序本身内存储 cocoa 应用程序的键值数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8282158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com