1

I've followed some other threads and successfully did the save/load custom objects to NSUserDefaults using NSCoding protocol. But, strange thing is: I can't update the object.

Here's some block of codes (Note: XUtil objectForKey: and setObject:forKey: is just perform load/save from NSUserDefaults)

// First, load the object.
+ (id)loadCustomObject 
{
    NSData *encodedObject = [XUtil objectForKey:@"customObject"];
    return encodedObject ? [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject] : nil;
}

Next, perform update its property, then:

// Finally, re-encode and save.
- (void)saveToDefault
{
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:self];
    [XUtil setObject:encodedObject forKey:@"customObject"];
}

So after a few try, I found out that there's something not right with KeyArchiver

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:(NSStringFromSelector(@selector(name))];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    self.name = [aDecoder decodeObjectforKey:(NSStringFromSelector(@selector(name))];
    return self;
}

First, load object, fine (name = @"ObjectName"). Update property (self.name = @"New Name"). Call [self saveToDefault].

I put debug after archivedDataWithRootObject:self in the second block:

po [[NSKeyedUnarchiver unarchiveObjectWithData:encodeObject] name]
-> old values

So the keyArchiver doesn't update the property, but I'm not sure what to do next.

EDIT5

After a day, tried all kind of possible methods, I've become so desperate and converted the whole NSCoder object to NSDictionary and save without any difficulty. What's the point of using this "Saving custom object to NSUserDefault" anyway.... People, please give me a light to this problem.

Eddie
  • 1,903
  • 2
  • 21
  • 46
  • Are you calling `[NSUserDefaults synchronize];`? If your class implements the `NSCoding` protocol correctly, then your code looks like it should work. The encoding of `"name"` is wrong for a start; the key should be `"name"` all the time. See [this](http://stackoverflow.com/questions/2315948/how-to-store-custom-objects-in-nsuserdefaults) question. – trojanfoe Dec 24 '15 at 11:35
  • in `XUtil setObject:ForKey` I did call synchronize. And I don't see why the encoding is wrong, the method `NSStringFromSelector(@selector())` return selector name, which is always `@"name"` – Eddie Dec 24 '15 at 13:21
  • But why such a round-about way of getting `@"name"`? It doesn't make it more robust or easier to read. It's unnecessary obfuscation. – trojanfoe Dec 26 '15 at 13:00
  • Well, you can say that I really dislike using hard code like that :/ Anyway, that shouldn't be any problem with the encode/ decode process. – Eddie Dec 26 '15 at 20:21

0 Answers0