Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Reflection for generic NSCoding implementation

Is there any means of reflection in Objective-C that would allow you to write generic NSCoding implementations by inspecting the public properties of an object and generating generic implementations of encodeWithCoder: and initWithCoder: .

I'm thinking of something like XStream for Java that allows a generic way to serialize and deserialize Java objects using reflection. Even better would probably be some means of marking properties as things you'd want to serialize or that are transient (like the transient keyword in Java).

I've been reading the documentation on Archives and Serializations Programming Guide for Cocoa. I understand that you want some control over the serialization of your objects, but it is generally a symmetrical process and it seems odd to have to reverse what is coded for serialization to deserialize it. I'm a believer of DRY (don't repeat yourself).

like image 970
Dougnukem Avatar asked May 28 '09 05:05

Dougnukem


1 Answers

Not only is it possible, but I have a friend who's taken a stab at doing precisely that. (You can see his blog about it here.) The reflection is done using the Objective-C runtime functions documented in the Objective-C 2.0 Runtime Reference. Take a look.

Note, however, that this will only work if you want the generic behavior of saving all the instance variables. You might not want an NSView to save its superview, though; in such cases, the generic case wouldn't work.

You could conceivably distinguish between things-to-serialize and things-not-to-serialize by declaring properties for any instance variables you want to save and leaving any other variables "hidden", but that's twisting the whole purpose of properties to a small benefit. I wouldn't recommend it.

like image 99
BJ Homer Avatar answered Nov 15 '22 17:11

BJ Homer