0

I need to save the OrderedDictionary to 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.

How is it?

How can I archive successfully the OrderedDictionary?

EDITED

The method initWithCoder is being called, but not encodeWithCoder

Community
  • 1
  • 1
Dejell
  • 13,947
  • 40
  • 146
  • 229

2 Answers2

1

Make sure your class conforms to the <NSCoding> protocoll (so your class definition reads @interface OrderedDictionary <NSCoding>)
Else, the framework doesn't know it should call encodeWithCoder:

Martin Ullrich
  • 94,744
  • 25
  • 252
  • 217
1

Please refer below link, may be will you get proper solution.

encodeWithCoder is not called in derived class of the NSMutableDictionary

When does encodeWithCoder get called?

Good Luck !!!!

Community
  • 1
  • 1
Dipak Narigara
  • 1,796
  • 16
  • 18