简体   繁体   English

将自定义OrderedDictionary存储到NSUserDefaults

[英]Storing custom OrderedDictionary to NSUserDefaults

I need to save the OrderedDictionary to NSUserDefaults. 我需要将OrderedDictionary保存到NSUserDefaults。

I read here and in many other posts how to do it: 在这里和许多其他帖子中读到如何做到这一点:

-(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"];
}

I then call it like this: 然后我这样称呼它:

 OrderedDictionary *od = [OrderedDictionary dictionaryWithDictionary:[businessInfo objectForKey:@"allowedStates"]];
    NSData *archivedObject = [NSKeyedArchiver archivedDataWithRootObject:od];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:archivedObject forKey:@"allowedStates"];
    [defaults synchronize];

and unarchive it like this: 并将其解压缩如下:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *archivedObject = [defaults objectForKey:@"allowedStates"];
    OrderedDictionary *countryStates = (OrderedDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:archivedObject];

I see that archivedObject is not empty, however countryStates is empty, although when I save it it's not empty. 我看到archivedObject不是空的,但是countryStates是空的,虽然当我保存它时它不是空的。

How is it? 如何?

How can I archive successfully the OrderedDictionary ? 如何成功存档OrderedDictionary

EDITED EDITED

The method initWithCoder is being called, but not encodeWithCoder 正在调用initWithCoder方法,但不是encodeWithCoder

Make sure your class conforms to the <NSCoding> protocoll (so your class definition reads @interface OrderedDictionary <NSCoding> ) 确保您的类符合<NSCoding> protocoll(因此您的类定义读取@interface OrderedDictionary <NSCoding>
Else, the framework doesn't know it should call encodeWithCoder: 否则,框架不知道它应该调用encodeWithCoder:

Please refer below link, may be will you get proper solution. 请参考以下链接,可能会得到适当的解决方案。

encodeWithCoder is not called in derived class of the NSMutableDictionary encodeWithCoder不在NSMutableDictionary的派生类中调用

When does encodeWithCoder get called? encodeWithCoder什么时候被调用?

Good Luck !!!! 祝好运 !!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM