您的位置:首页 > 移动开发 > IOS开发

ios developer tiny share-20161020

2016-11-01 22:31 176 查看
本节讲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:)];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息