NSDictionary Vs. NSArray

你。 提交于 2019-12-04 08:53:56
Florian

NSArray is basically just an ordered collection of objects, which can be accessed by index.
NSDictionary provides access to its objects by key(typically NSStrings, but could be any object type like hash table).

To generate an object graph from a JSON string loaded via a URL, you use NSJSONSerialization, which generates an Objective-C object structure. The resulting object depends on the JSON string. If the top-level element in your JSON is an array (starts with "["), you'll get an NSArray. If the top-level element is a JSON object (starts with "{"), you'll get an NSDictionary.

You want to use NSArray when ever you have a collection of the same type of objects, and NSDictionary when you have attributes on an object.

If you have, lets say a person object containing a name, a phone number and an email you would put it in a dictionary.

Doing so allows the order of the values to be random, and gives you a more reliable code.

If you want to have more then one person you can then put the person objects in an array.

Doing so allow you to iterate the user objects.

"withContentOfURL" or "withContentOfFile" requires the data in the URL or the file to be in a specific format as it is required by Cocoa. JSON is not that format. You can only use these methods if you wrote the data to the file or the URL yourself in the first place, with the same data. If you write an NSArray, you can read an NSArray. If you write an NSDictionary, you can read an NSDictionary. Everything else will fail.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!