天天看點

ios developer tiny share-20161020

本節講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:)];