ios developer tiny share-20161031

本文介绍了Objective-C中使用Enumerator对象遍历集合的方法,包括正序和逆序遍历,并对比了快速遍历的方式。

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

今天把Objective-C的集合这一节收尾,讲另一种集合的遍历,即使用Enumerator。

下面是ios reference官方的讲解:



Most Collections Also Support Enumerator Objects

It’s also possible to enumerate many Cocoa and Cocoa Touch collections by using an NSEnumerator object.


You can ask an NSArray, for example, for an objectEnumerator or a reverseObjectEnumerator. It’s possible to use these objects with fast enumeration, like this:
for (id eachObject in [array reverseObjectEnumerator]) {
	...
}

In this example, the loop will iterate over the collected objects in reverse order, so the last object will be first, and so on.

It’s also possible to iterate through the contents by calling the enumerator’s nextObject method repeatedly, like this:

id eachObject;
while ( (eachObject = [enumerator nextObject]) ) {
	NSLog(@"Current object is: %@", eachObject);
}

In this example, a while loop is used to set the eachObject variable to the next object for each pass through the loop. When there are no more objects left, the nextObject method will return nil, which evaluates as a logical value of false so the loop stops.

Note: Because it’s a common programmer error to use the C assignment operator (=) when you mean the equality operator (==), the compiler will warn you if you set a variable in a conditional branch or loop, like this:

if (someVariable = YES) {
    ...
}

If you really do mean to reassign a variable (the logical value of the overall assignment is the final value of the left hand side), you can indicate this by placing the assignment in parentheses, like this:

if ( (someVariable = YES) ) {
    ...
}

As with fast enumeration, you cannot mutate a collection while enumerating. And, as you might gather from the name, it’s faster to use fast enumeration than to use an enumerator object manually.


Many Collections Support Block-Based Enumeration
It’s also possible to enumerate NSArray, NSSet and NSDictionary using blocks. Blocks are covered in detail in the next chapter.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值