gpt4 book ai didi

IOS - 将 NSDictionary 保存到磁盘

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:17:41 30 4
gpt4 key购买 nike

我有一个 NSDictionary,它包含一堆以 NSDates 为键的数组,每个数组包含数量可变的 NSString

像这样:

NSDictionary

Key: 1999-whatever-whatever
Object: (Array)
"Some string"
"Some other string"

Key: 2000-whatever-whatever
Object: (Array)
"Some third string"

我一直在研究 writeToFile,但它似乎不支持具有 NSDates 键的 NSDictionary,所以我研究了 KeydArchiver,这是最好的方法吗?

如果是,任何有关该主题的教程都会有所帮助。

感谢您的宝贵时间。

PS:我想我应该在 ApplicationWillTerminate 上进行保存?

最佳答案

编辑——我没意识到你的问题说的是 iOS。所以请忽略我将字典保存到桌面的方式,但将 NSDate 保存为字符串的方法是相同的。

如果您更改保存 NSDictionary 的方式,则不必进入 KeydArchiver。

NSDictionary

Key: 1999-08-13 //<----- Have this as a string in your dictionary. Not NSDate
Object: (Array)
"Some string"
"Some other string"

Key: 2000-08-13 //<------Have this as a string in your dictionary. Not NSDate
Object: (Array)
"Some third string"

当你想将 NSDictionary 保存到一个文件中时,你可以这样做:

[MyDictionary writeToFile:@"/Users/yourUsername/Desktop/mySavedDictionary.plist" atomically:YES];

如果要重新加载字典:

NSDictionary *myDictionary = [NSDictionary dictionaryWithContentsOfFile:@"/Users/yourUsername/Desktop/mySavedDictionary.plist"];

加载字典后,假设您想获取存储在日期 2000-08-13 的数据,那么您可以这样做:

我首先假设 NSDate myPreviouslyDeclaredDate 是您要在字典中查找的日期,并且其格式为 yyyy-MM-dd。您可以选择任何您想要的格式。使用 AppleDocs作为指南。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSString *previouslyDeclaredDateInStringForm = [dateFormatter dateFromString:myPreviouslyDeclaredDate];
id objectNeededFromDictionary = [myDictionary objectForKey:previouslyDeclaredDateInStringForm];

关于IOS - 将 NSDictionary 保存到磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18196728/

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