天天看點

ios developer tiny share-20161025

今天講Objective-C的字典NSDictionary。

Dictionaries Collect Key-Value Pairs

Rather than simply maintaining an ordered or unordered collection of objects, an NSDictionary stores objects against given keys, which can then be used for retrieval.

It’s best practice to use string objects as dictionary keys, as shown in Figure 6-3.

Figure 6-3  A Dictionary of Objects

ios developer tiny share-20161025

Note: It’s possible to use other objects as keys, but it’s important to note that each key is copied for use by a dictionary and so must support NSCopying.

If you wish to be able to use Key-Value Coding, however, as described in Key-Value Coding Programming Guide, you must use string keys for dictionary objects.

Creating Dictionaries

You can create dictionaries using either allocation and initialization, or class factory methods, like this:

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
			   someObject, @"anObject",
		 @"Hello, World!", @"helloString",
					  @42, @"magicNumber",
				someValue, @"aValue",
						 nil];
           

Note that for the dictionaryWithObjectsAndKeys: and initWithObjectsAndKeys: methods, each object is specified before its key, and again, the list of objects and keys must be nil-terminated.

Literal Syntax

Objective-C also offers a literal syntax for dictionary creation, like this:

NSDictionary *dictionary = @{
			  @"anObject" : someObject,
		   @"helloString" : @"Hello, World!",
		   @"magicNumber" : @42,
				@"aValue" : someValue
};
           

Note that for dictionary literals, the key is specified before its object and is not nil-terminated.