本节讲Objective-C数组的遍历和排序
Querying Array Objects
Once you’ve created an array, you can query it for information like the number of objects, or whether it contains a given item:
NSUInteger numberOfItems = [someArray count];
if ([someArray containsObject:someString]) {
...
}You can also query the array for an item at a given index. You’ll get an out-of-bounds exception at runtime if you attempt to request an invalid index, so you should always check the number of items first:
if ([someArray count] > 0) {
NSLog(@"First item is: %@", [someArray objectAtIndex:0]);
}This example checks whether the number of items is greater than zero. If so, it logs a description of the first item, which has an index of zero.
Subscripting
There’s also a subscript syntax alternative to using objectAtIndex:, which is just like accessing a value in a standard C array. The previous example could be re-written like this:
if ([someArray count] > 0) {
NSLog(@"First item is: %@", someArray[0]);
}
Sorting Array Objects
The NSArray class also offers a variety of methods to sort its collected objects. Because NSArray is immutable, each of these methods returns a new array containing the items in the sorted order.
As an example, you can sort an array of strings by the result of calling compare: on each string, like this:
NSArray *unsortedStrings = @[@"gammaString", @"alphaString", @"betaString"];
NSArray *sortedStrings =
[unsortedStrings sortedArrayUsingSelector:@selector(compare:)];
本文介绍如何使用Objective-C查询数组信息,如元素数量、特定项是否存在等,并提供了通过索引来访问数组元素的方法。此外,还详细讲解了如何使用NSArray类提供的方法来对数组中的对象进行排序。
233

被折叠的 条评论
为什么被折叠?



