天天看點

Brief Intro to Collections of Foundation Frameworks

Collections

The Foundation Framework collections classes manage collections of objects. Most collection classes have both an immutable and a mutable version. NSArray and NSMutableArray manage arrays, ordered collections of objects that can be of any type; the elements of an NSArray do not have to be of the same type. NSDictionary and NSMutableDictionary are used for groups of key-value pairs.NSSet, NSMutableSet, and NSCountedSet are used to manage unordered collections of objects. TheNSEnumerator and NSDirectoryEnumerator classes enumerate collections of other objects, such as arrays and dictionaries. NSIndexSet and NSMutableIndexSet manage collections of index sets(collections of unique unsigned integers used to store indexes into another data structure).NSHashTable, NSMapTable, and NSPointerArray are mutable collections that support weak relationships when using the garbage collector.

The NSHashTable, NSMapTable, and NSPointerArray classes are available for use on the Apple OS X platform only (i.e., these classes are not available for the iOS platform).

NSArray

NSArray and NSMutableArray manage ordered collections of objects that do not have to be of the same type. NSArray is immutable (the objects assigned to the array at initialization cannot be removed, although there contents can be changed). NSMutableArray allows adding or removing objects in a collection. The operations supported by NSArray include array creation and initialization, query (obtaining information about the array or retrieving its elements), finding an object in an array, object messaging to array elements, comparing arrays, and sorting an array. Many NSArray andNSMutableArray operations are executed in constant time (accessing an element, adding/removing on ends, replacing an element), whereas inserting an element in the middle of an NSMutableArraytakes linear time. The following statement uses the NSArray arrayWithObjects: convenience constructor to create an NSArray object assigned to the variable myArray initialized with NSNumberliterals.

NSArray *myArray = [NSArray arrayWithObjects:@1, @2, nil];      

Notice that the arrayWithObjects: method requires parameters with a comma-separated list of objects ending with nil. The next statement retrieves the first element of this NSArray object using the NSArray indexOfObject: method.

id num0 = [myArray objectAtIndex:0];      

The following statement returns the index of the NSNumber object (with a value of 2) in the precedingNSArray object.

NSUInteger index = [myArray indexOfObject:@2];      

NSArray also includes the following methods to persist the contents of an array to a property list and initialize an NSArray object from a property list:

- writeToFile:atomically:
- writeToURL:atomically:
- initWithContentsOfFile:
- initWithContentsOfURL:      

When persisting an array (via the writeTo... methods), its contents must all be property list objects (i.e., NSString, NSData, NSDate, NSNumber, NSArray, NSDictionary objects).

NSArray Literals

Objective-C provides language-level support for creating NSArray literals. The array is defined by a comma-separated list of objects between square brackets, prefixed by an @ character. Unlike the NSArray arrayWithObjects: and initWithObjects: methods, the list of objects used to define anNSArray literal is not required to end with a nil. The following statements are equivalent:

NSArray *myArray = [NSArray arrayWithObjects:@1, @2, nil];
NSArray *myArray = @[@1, @2];      

As with NSNumber literals, NSArray literals are not compile-time constants; they are evaluated at runtime.

NSPointerArray

NSPointerArray is a mutable collection similar to NSMutableArray that can hold arbitrary pointers and NULL values. It also allows you to manage the collection by setting the count for the array, such that if the number of elements in the collection is less than the count, then the collection is padded with NULL values; or if the number of elements in the collection is greater than the count, then the elements in the collection above the count value are removed.

NSDictionary

The NSDictionary and NSMutableDictionary classes manage collections of key/value (object) pairs. Within a collection, the value of a key is unique (i.e., it must be an object that adopts the NSCopyingprotocol and implements the hash and isEqual: methods). The operations supported by these classes include object creation and initialization, query, finding objects in the collection, filtering, comparing, and sorting the collection. The sorting options include sorting with selectors (using thekeySortedByValueUsingSelector: method), and sorting with blocks (using thekeySortedByValueUsingComparator: method). For keys with good hash functions (for example, NSString), NSDictionary operations take constant time (accessing, setting, removing an element from an NSDictionary or NSMutableDictionary). The code fragment shown in Listing 10-5 creates and initializes an NSDictionary object with two elements.

Listing 10-5.  Creating and Initializing an NSDictionary Object

NSArray *objects = @[@1, @2];
NSArray *keys = @[@"one", @"two"];
NSDictionary *myDi = [NSDictionary dictionaryWithObjects:objects];
                       withKeys:keys];      

The next statement retrieves the value from the preceding NSDictionary object that has the key"one".

id value = [myDi objectForKey:@"one"];      

As with NSArray, NSDictionary includes methods to persist the contents of a dictionary to a property list and initialize an NSDictionary object from a property list:

- writeToFile:atomically:
- writeToURL:atomically:
- initWithContentsOfFile:
- initWithContentsOfURL:      

When persisting a dictionary (via the writeTo... methods), its contents must all be property list objects (NSString, NSData, NSDate, NSNumber, NSArray, and NSDictionary objects).

NSDictionary Literals

Objective-C provides language-level support for creating NSDictionary literals. The dictionary is defined by a comma-separated list of key-value pairs between curly braces, prefixed by an @character. In each key-value pair, a colon separates the key and value. The following statements are equivalent:

NSArray *objects = @[@1, @2];
NSArray *keys = @[@"one", @"two"];
NSDictionary *myDi = [NSDictionary dictionaryWithObjects:objects];

NSDictionary *myDi = @{@"one":@1, @"two":@2};      

As with NSNumber literals, NSDictionary literals are not compile-time constants; they are evaluated at runtime.

NSMapTable

NSPointerArray is a mutable collection similar to NSDictionary that provides additional storage options. Specifically, it can store arbitrary pointers. It can also store weakly referenced keys and/or values.

NSSet

NSSet and NSMutableSet manage unordered collections of objects that do not have to be of the same type. The objects stored in an NSSet are unique. The operations supported by NSSet include creation and initialization, finding an object in a set, comparing, and sorting (using the NSSetsortedArrayUsingDescriptors: method). If the objects in the set have a good hash function, accessing an element, setting an element, and removing an element all take constant time. With a poor hash function (one that causes frequent hash collisions), these operations take up linear time.

Sets, excluding NSCountedSets, ensure that no object is represented more than once, and there is nonet effect for adding an object more than once. The following statement uses the NSSet setWithObjects: convenience constructor to create an NSSet object assigned to the variable mySetinitialized with NSNumber literals.

NSSet *mySet = [NSSet setWithObjects:@1, @2, nil];      

NSCountedSet

NSCountedSet is a mutable set that allows an object to be added multiple times (i.e., its elements aren’t required to be distinct). Each distinct object has an associated counter. An NSSet object keeps track of the number of times each distinct object is inserted and requires a corresponding object(s) to be removed the same number of times.

NSHashTable

NSHashTable is a mutable collection similar to NSSet that provides different options. Specifically, it can store arbitrary pointers. It can also store weakly referenced keys and/or values.

NSPointerFunctions

The NSPointerFunctions class defines functions for managing pointer functions. An NSHashTable ,NSMapTable , or NSPointerArray object typically uses an NSPointerFunctions instance to define behavior for the pointers it manages.