Question

We want to take XML data and convert it to an NSDictionary object, but we don't want to manually iterate over the XML. Is there an easy way to do this? How are you doing web services for your iPhone app?

Was it helpful?

Solution

If you have control over the XML output you could try creating a property list which you can then read into a dictionary using -dictionaryWithContentsOfURL: (though the better asynchronous way would be to get the data using an NSURLConnection and then converting the data using the -propertyList method on NSString). You can find more about property lists here: http://developer.apple.com/documentation/Cocoa/Conceptual/PropertyLists/Introduction/chapter_1_section_1.html

Of course the best solution is to use a RESTful client and use a combination of NSURLConnection to get/send the data and the TouchXML classes (http://code.google.com/p/touchcode/wiki/TouchXML) to parse the data, though this would require more work to put the data into a dictionary. Of course if these are going to be the main data objects in your system you really want to be using either a custom class or SQLite to store the data as it provides you much more reliability in testing your app than a dictionary.

OTHER TIPS

If you can control the server output, try using plists. Otherwise you're stuck with parsing XML (or JSON if the server can do that), but there are frameworks you can use. See the answer to this question.

Also, here is a good overview of how to do RESTful clients on the iphone:

https://developer.apple.com/webapps/articles/creatingrestfulclients.html

You can return the data in JSON format. There are many open-source JSON parsers available for the iPhone (TouchJSON being one).

There's another class available called NSPropertyListSerialization which gets you a dictionary from data.

You can do something like this with the data you receive

NSDictionary* propertyList;
NSPropertyListFormat format;
NSString *errorStr;

propertyList = [NSPropertyListSerialization
propertyListFromData:receivedData
mutabilityOption: NSPropertyListImmutable
format: &format
errorDescription: &errorStr];

Sorry, don't know what tags are used here for formatting code!

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