Question

I like the plist serialization capability for small collections of objects: it is simple, the storage is XML, etc. But I find setting values in dictionaries cumbersome:

[myDict setObject:keepThis forKey:@"ivar"];

I'd much prefer to use object derived of classes (or even just structs):

myObj.ivar = keepThis

... and then send a message to a collection to get a plist. The classes/structs used for this purpose could be restricted so that they map directly and easily to plist primitives; for example myObj could be mapped to a NSDictionary and a requirement could be placed on ivars such that they are one of the plist primitives.

Has someone already built a facility for this, or should I roll my own?

Was it helpful?

Solution 5

I saw this posted elsewhere, but it is exactly what I was looking for. The answers above point to the raw ingredients, but here it is, all wrapped-up: http://retaincount.com/blog/?p=7

OTHER TIPS

I'm not sure that this is quite what you're talking about, but Key Value Coding will, among many other things, let you get a dictionary with values from an instance's data, and also set instance data from a dictionary.

There's also a way to ask an instance for a list of its attributes, though it turns out that you have to write some code yourself to make that work. (You, could, though, use the runtime introspection to implement that, if you wanted.) EDIT 2 January 2011: -[NSObject attributeKeys] no longer appears in the iOS documentation. I've edited the link to point to the Mac documentation, but be aware that this may only be an option on that platform.

(The NSCoding protocol is another way of letting your objects store/restore themselves, but the storage is binary, not XML, and you are still responsible for getting/putting each value you care about when asked by the system to do so.)

You might want to check out this SO question which discusses putting an instance's ivars in a dictionary at runtime.

An interesting project. The Objective-C 2.0 Programming Guide has a section on the runtime functions to dynamically get a list of a class's properties:

objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)

With this, it should be quite easy to write a category on NSObject with a method that gets the list of properties and puts them into a dictionary.

In order to use properties for this, you would need to have a predefined set of possible keys. You can't use arbitrary names with the dot-syntax — it had to be a known property or accessor of the first operand. So there can't be a generic form of this. But if you do make one of your own, turning into a dictionary is as simple as doing [self dictionaryWithValuesForKeys:listOfProperties].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top