English 中文(简体)
有没有一个简单的方法来为iPhone开发使用Web服务?
原标题:
  • 时间:2008-12-30 13:57:05
  •  标签:

我们想要将XML数据转换为NSDictionary对象,但是我们不想手动迭代XML。有没有简单的方法可以做到这一点?你是如何为你的iPhone应用程序做网络服务的?

最佳回答

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.

问题回答

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!





相关问题
热门标签