将 NSDictionary 保存到文件是否有任何限制 [英] Is there any restrictions on save NSDictionary to file

查看:56
本文介绍了将 NSDictionary 保存到文件是否有任何限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用下面的方法保存NSDictionary

I want to use the following method to save NSDictionary

+ (void)writeDicToFile:(NSDictionary *)dic fileName:(NSString *)fileName
{
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
[dic writeToFile:filePath atomically:YES];
}

但是对于某些字典它有效,而对于某些复杂的字典它不起作用.

But for some dictionary it works and for some complex dictionary it doesn't work.

帮帮我!

推荐答案

为了使 NSDictionary 成功保存,它持有的所有对象都必须符合 NSCoding 协议.

In order for NSDictionary to be successfully saved all the objects it holds have to conform to NSCoding protocol.

简而言之,这意味着您必须实施

In short that means that you have to implement

- (void)encodeWithCoder:(NSCoder *)encoder

- (id)initWithCoder:(NSCoder *)decoder

适用于所有自定义类.

一个不错的教程在这里:http://www.raywenderlich.com/1914/nscoding-tutorial-for-ios-how-to-save-your-app-data

A nice tutorial is here: http://www.raywenderlich.com/1914/nscoding-tutorial-for-ios-how-to-save-your-app-data

一旦你编写了 NSCoder 方法,你就可以像这样保存数据:

Once you have written you NSCoder methods you can save data like this:

NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:self];
[archiver finishEncoding];
[data writeToFile:file atomically:YES];

然后像这样从文件中初始化对象:

And init the object from file like this:

NSData *data = [[NSData alloc] initWithContentsOfFile:file];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
self = [unarchiver decodeObject];
[unarchiver finishDecoding];

你确实提到了 json 对象有问题:关于 json 对象的事情是首先你必须检查它的类型:它可以是 NSDictionaryNSArray -取决于输入和格式.

You did mention having problems with json object: the thing about json object is that first you have to check its type: it can be a NSDictionary or a NSArray - depending on the input and format.

当你得到一个只有一个元素的数组时会出现常见的问题 - 你正在寻找的字典.如果您的字典 {...} json 表示嵌入在 [] 中,就会发生这种情况.

Common problem occours when you get an array with only one element - dictionary you are looking for. This happens if your dictionary {...} json representation is embedded within [].

这篇关于将 NSDictionary 保存到文件是否有任何限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆