今天讲Objective-C的Collection的Array。
Arrays Are Ordered Collections
An NSArray is used to represent an ordered collection of objects. The only requirement is that each item is an Objective-C object— there’s no requirement for each object to be an instance of the same class.
To maintain order in the array, each element is stored at a zero-based index, as shown in Figure 6-1.
Figure 6-1 An Array of Objective-C Objects
Creating Arrays
As with the value classes described earlier in this chapter, you can create an array through allocation and initialization, class factory methods, or literal syntax.
There are a variety of different initialization and factory methods available, depending on the number of objects:
+ (id)arrayWithObject:(id)anObject;
+ (id)arrayWithObjects:(id)firstObject, ...;
- (id)initWithObjects:(id)firstObject, ...;
The arrayWithObjects: and initWithObjects: methods both take a nil-terminated, variable number of arguments, which means that you must include nil as the last value, like this:
NSArray *someArray =
[NSArray arrayWithObjects:someObject, someString, someNumber, someValue, nil];
This example creates an array like the one shown earlier, in Figure 6-1. The first object, someObject, will have an array index of 0; the last object, someValue, will have an index of 3.
It’s possible to truncate the list of items unintentionally if one of the provided values is nil, like this:
id firstObject = @"someString";
id secondObject = nil;
id thirdObject = @"anotherString";
NSArray *someArray =
[NSArray arrayWithObjects:firstObject, secondObject, thirdObject, nil];
In this case, someArray will contain only firstObject, because the nil secondObject would be interpreted as the end of the list of items.
Literal Syntax
It’s also possible to create an array using an Objective-C literal, like this:
NSArray *someArray = @[firstObject, secondObject, thirdObject];
You should not terminate the list of objects with nil when using this literal syntax, and in fact nil is an invalid value. You’ll get an exception at runtime if you try to execute the following code, for example:
id firstObject = @"someString";
id secondObject = nil;
NSArray *someArray = @[firstObject, secondObject];
// exception: "attempt to insert nil object"
If you do need to represent a nil value in one of the collection classes, you should use the NSNull singleton class, as described in Represent nil with NSNull.