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.