我需要将OrderedDictionary保存到NSUserDefaults。
我阅读here以及许多其他帖子中的操作方法:
-(id)initWithCoder:(NSCoder *)decoder{
if (self != nil){
dictionary = [decoder decodeObjectForKey:@"dictionary"];
array = [decoder decodeObjectForKey:@"array"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)encoder{
[encoder encodeObject: dictionary forKey:@"dictionary"];
[encoder encodeObject: array forKey:@"array"];
}
然后我这样称呼它:
OrderedDictionary *od = [OrderedDictionary dictionaryWithDictionary:[businessInfo objectForKey:@"allowedStates"]];
NSData *archivedObject = [NSKeyedArchiver archivedDataWithRootObject:od];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:archivedObject forKey:@"allowedStates"];
[defaults synchronize];
并将其解压缩如下:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *archivedObject = [defaults objectForKey:@"allowedStates"];
OrderedDictionary *countryStates = (OrderedDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:archivedObject];
我看到archivedObject
不为空,但是countryStates
为空,但是当我保存它时它不是空的。
怎么回事?
如何成功归档OrderedDictionary
?
EDITED
正在调用initWithCoder方法,但不是encodeWithCoder
答案 0 :(得分:1)
确保您的班级符合<NSCoding>
协议1(因此您的班级定义为@interface OrderedDictionary <NSCoding>
)
否则,框架不知道它应该调用encodeWithCoder:
答案 1 :(得分:1)
请参考以下链接,可能会得到正确的解决方案。
encodeWithCoder is not called in derived class of the NSMutableDictionary
When does encodeWithCoder get called?
祝你好运!!!!