NSCoding with Nested Custom Objects?

*爱你&永不变心* 提交于 2019-12-01 03:26:23

Yes, you can (and probably should) write your support for NSCoding to be recursive. That's how NSCoding is supposed to work.

When your implement encodeWithCoder, simply call

[coder encodeObject: aProperty forKey: @"propertyName"];

on all your object's properties, including it's container properties.

Then make sure every object in your object's object graph also conforms to NSCoding.

For scalar properties, you can save the scalar value using NSCoder methods like encodeInt:forKey:

To save an object that conforms to NSCoding to user defaults, first convert it to NSData using the NSKeyedArchiver class method archivedDataWithRootObject, then save the resulting data into defaults. Quite simple, really.

NSCoding isn't magic so it will work 'recursively' if your implementation of the encoding and decoding methods tells it to be.

Implement the NSCoding methods and pass the data to be encoded to the encoder. Implement the NSCoding methods in all of your custom classes so that when you encode the array all of the contents can be processed appropriately.

Be sure to call super if the classes superclass also implements NSCoding.

e.g.

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.arrayOfClasses forKey:@"arrayOfClasses"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    self.arrayOfClasses = [decoder decodeObjectForKey:@"arrayOfClasses"];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!