今天把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.