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

发布于 2024-09-25 12:23:42 字数 116 浏览 0 评论 0原文

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

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

I want to save an NSMutableArray or NSDictionary as a permanent file. Then, I would like to reopen the file later.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不乱于心 2024-10-02 12:23:42

写入文件

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

[myArray writeToFile:filePath atomically:YES];

如果文件不存在,则从文件读取

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

myArray = [NSArray arrayWithContentsOfFile:filePath];

myArray 将为 nil。 NSDictionary也有类似的方法。请检查参考资料以了解这些方法的详细信息。

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.

念三年u 2024-10-02 12:23:42

也许您可以将字典转换为 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];
}

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

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];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文