ios developer tiny share-20161020

本文介绍如何使用Objective-C查询数组信息,如元素数量、特定项是否存在等,并提供了通过索引来访问数组元素的方法。此外,还详细讲解了如何使用NSArray类提供的方法来对数组中的对象进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本节讲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:)];


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值