NSCoding with Nested Custom Objects?

前端 未结 2 1866
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-11 14:57

I have a series of nested objects that I am needing to put through the NSCoding protocol so that I can save the top level object into NSUserDefaults.

Here is the st

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-11 15:14

    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.

提交回复
热议问题