NSDictionary Vs. NSArray

2019-04-09 01:49发布

I am reading on objective-c (a nerd ranch book), and I can't help thinking about this question: How do I decide which collection type, NSArray or NSDictionary (both with or w/o their mutable subclasses), to use when reading content from URL?

Let's say am reading JSON data from a PHP script (a scenario am dealing with), which to use? I know it is stated in many references that it depends on structure of data (i.e. JSON), but could a clear outline of the two structures be outlined?

Thank you all for helping :)

3条回答
男人必须洒脱
2楼-- · 2019-04-09 02:09

"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.

查看更多
叼着烟拽天下
3楼-- · 2019-04-09 02:13

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-09 02:29

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.

查看更多
登录 后发表回答