简体   繁体   中英

How to implement NSCoding for Properties and ivars automatically

I am trying to save a lot of objects to a file and retrieve them for later use.

Previously, I used these macros - it felt tedious though.

Then I discovered Autocoding , which is awesome in its own way but it can't encode/decode instance variables.

I am in need of automating the whole process of encoding/decoding since my app is still under development and it's tedious to write encode/decode implementation for every ivar.

You could just overide the +codableProperties method and return the names of the ivars. It's not as nice as detecting them automatically, but nicer than writing the NSCoding logic manually.

You can get the list of ivars associated with a class from the Objective-C runtime -- see the class_copyIvarList function. Likewise, you can get the value of an ivar for a specific object using object_getIvar and set it with object_setIvar . These seem like the main tools you'd need to automatically encode an object's ivars.

One place you'll need to be careful is that you won't want to save both the value for a property and the value for the ivar that backs it. So you'll probably want to compare the list of ivars to the list of properties, and only encode/decode those ivars for which there doesn't seem to be a corresponding property.

Also, it's not always desirable to make every last bit of an object's state persistent, so you should consider providing a way to opt out for specific ivars (which might in the end be just as tedious as opting in). As well, you'll probably need to determine which ivars you even can encode, eg the usual value types and any types which themselves implement NSCoding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM