是否可以将 NSMutableArray 或 NSDictionary 数据保存为 iOS 中的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3829631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:48:57  来源:igfitidea点击:

is it possible to save NSMutableArray or NSDictionary data as file in iOS?

ioscocoa-touchnsmutablearraynsdictionarynsdata

提问by RAGOpoR

I want to save an NSMutableArrayor NSDictionaryas a permanent file. Then, I would like to reopen the file later.

我想将NSMutableArray或保存NSDictionary为永久文件。然后,我想稍后重新打开该文件。

Is this possible? If so, how can I do it?

这可能吗?如果是这样,我该怎么做?

回答by taskinoor

To write in file

写入文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];

[myArray writeToFile:filePath atomically:YES];

To read from file

从文件中读取

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];

myArray = [NSArray arrayWithContentsOfFile:filePath];

myArray will be nil if file is not present. And NSDictionary has similar methods. Please check the reference for the details of these methods.

如果文件不存在,myArray 将为 nil。而 NSDictionary 也有类似的方法。请查看参考资料以了解这些方法的详细信息。

回答by Hancock_Xu

May be you can convert a Dictionary to JSON data.and write it to a file.

也许您可以将字典转换为 JSON 数据。并将其写入文件。

NSDictionary *dict = /* the NSDictionary/NSArray you need to write */

NSError *writeError = nil;
NSData* data;
data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&writeError];

if (!writeError) {
    [data writeToFile:filePath atomically:YES];
}