Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
643 views
in Technique[技术] by (71.8m points)

objective c - What's the difference between a dictionary and an array?

What is the difference between a dictionary and an array, especially when working with PLIST files? What are the advantages of using one over the other? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Both NSDictionary and NSArray are collection classes, i.e. the group together other objects.

An NSArray is an 'ordered collection' - every item in the collection has an integer index, so there is an explicit order to the items. If you swap the order of items in the collection then the collection is no longer the 'same' as the order is different. An object may appear more than once in the collection.

An NSSet is an 'unordered collection' - every item appears in a bag, the order doesn't matter and an object can only exist once in the bag.

An NSDictionary is an 'indexed collection' - every item in the collection has a key and can be retrieved with that key. An object may appear more than once, in that different keys may point to the same object, but a key can only appear once. A dictionary is also a form of 'hash table' if you have a computer science background.

When parsing PLISTs, Arrays and Dictionaries are the main types you deal with. When you edit a PLIST in Xcode - if you set something as an Array type, then all of it's children are listed as "Item 0, Item 1, Item 2..." whereas if you set it as a Dictionary type, then it's children are key:value pairs.

One significant use case for the difference types is as follows.

Imagine a magazine application which contains a number of articles. The order of the articles is important, and so you would store each article in an array. If you wanted to change the order of the articles, you would change the order of the array in the plist.

The articles themselves may be represented by Dictionaries, perhaps containing keys such as "TextFile", "Background", "ArticleType". You use a Dictionary because you may add more information to the dictionary at some point in the future, and the key:value mechanism makes your code understandable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...