ios developer tiny share-20161019

今天讲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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值