views:

2515

answers:

2

I had a straight forward approach of turning Key/Value pairs of an XML excerpt into an NSDictionary when I started a simple iPhone application. The problem is, I need to turn those NSDictionary's instances that once populated my UITableView's into custom classes because they require behavior and additional complexity. The problem here is that now in order for me to instantiate an object and fill its instance variables with key/value pairs from a web service becomes that much more difficult. I can no longer throw it into a method that iterates through the XML and uses KVC to set its instance variables.

What kind of other solution is out there?

+1  A: 

Look into NSCoding. You can use the NSCoding protocol to save your object, properties and all, as data.

Once your object is NSCoding compliant, you can just archive the whole array of objects using NSKeyedArchiver.

Please note that if you have a large number of objects, this can dramatically affect the app's performance on the iPhone during load and save.

August
NSCoding looks like a great solution, August. I am concerned though with the performance penalty for using it. My objects typically contain 5/6 instance variables, fundamental data types. I wonder how many it would take to tank my app.
Coocoo4Cocoa
He's working with an XML web service though, not asking how to persist his objects to a data source.
Marc Charbonneau
Affect positively or negatively ?
Harald Scheirich
Charbonneau is correct. I get an XML feed in which corresponds to an object on the iPhone/Mac client. Typically it'll be something like <user><name>Bob</name><age>43</age></user> I had a method before that would key/value code NSDictionary instances.
Coocoo4Cocoa
+6  A: 

You can still use key value coding methods on your custom class, as long as you name your variables appropriately there's no difference there. With that being said though, when I'm working with XML I usually end up testing each node name or creating a key lookup table, since the names in the data source I'm working with aren't key value coding compliant. If you have control over the data source though, you could just continue to use setValue:forKey:.

I'd recommend reading this guide about key value coding if you haven't already. It's fundamental to many great tools in Cocoa.

Marc Charbonneau
That sounds good, Marc. Any chance you can explain what you mean that names in the data source aren't key/value coding compliant? And what do you test your nodes for?
Coocoo4Cocoa
Capitalization plays a part, but also node names don't always match the variable name. For example, DetailPageURL might map to pageURL, Title to title, and so on.
Marc Charbonneau