views:

22

answers:

1

I am using KVC to set properties of objects from a plist. I know I can save them as strings <string>{{66, 114}, {64, 64}}</string> and manually convert to structs, but how can I save for example a CGPoint or CGRect in a plist in a way that Cocoa KVC would understand? The Key-Value Coding Programming Guide seems to indicate that I need to save them as NSValues. How?

+2  A: 

The Key-Value Coding Programming Guide seems to indicate that I need to save them as NSValues.

No, you need an NSValue to pass a point or rectangle to setValue:forKey:. The KVC docs aren't talking about saving the values anywhere, since that isn't part of KVC. And you can't save an NSValue in a property list, since it isn't one of the property list classes.

So, you need to convert the rectangle to and from one of the property-list data types. I prefer to convert them to and from strings, which you can do with some of the functions in UIKit.

These are actually Core Graphics structures, not UIKit (hence the names CGPoint and CGRect), so you might expect Core Graphics to have functions for this. Indeed it does, but of a different sort: In CGGeometry, Core Graphics provides functions to convert CGPoints and CGRects to and from dictionaries.

Strings or dictionaries: It's your choice. Whichever you choose, they are property lists, so you can store them in your property list output.

On retrieval, convert the dictionary or string to a point or rectangle, and create an NSValue with that to pass to setValue:forKey:. Of course, this works in reverse the other way: When saving, valueForKey: will give you an NSValue, from which you need to extract the point or rectangle to convert to a dictionary or string to save in the plist.

Peter Hosey
Thanks for the info! It looks like strings are easier because I want to edit the plists.
hyn