ios developer tiny share-20161028

来源:互联网 发布:淘宝上如何买衣服 编辑:程序博客网 时间:2024/05/22 00:12

今天讲Objective-C集合类的遍历,除了可以使用普通C语言的遍历外,还可以使用Objective-C特有的增强for循环。


下面是ios官方api的说明。


Fast Enumeration Makes It Easy to Enumerate a Collection


Many collection classes conform to the NSFastEnumeration protocol, including NSArray, NSSet and NSDictionary. This means that you can use fast enumeration, an Objective-C language-level feature.

The fast enumeration syntax to enumerate the contents of an array or set looks like this:

for (<Type> <variable> in <collection>) {...}

As an example, you might use fast enumeration to log a description of each object in an array, like this:

for (id eachObject in array) {NSLog(@"Object: %@", eachObject);}

The eachObject variable is set automatically to the current object for each pass through the loop, so one log statement appears per object.

If you use fast enumeration with a dictionary, you iterate over the dictionary keys, like this:

for (NSString *eachKey in dictionary) {id object = dictionary[eachKey];NSLog(@"Object: %@ for key: %@", object, eachKey);}

Fast enumeration behaves much like a standard C for loop, so you can use the break keyword to interrupt the iteration, or continue to advance to the next element.

If you are enumerating an ordered collection, the enumeration proceeds in that order. For an NSArray, this means the first pass will be for the object at index 0, the second for object at index 1, etc. If you need to keep track of the current index, simply count the iterations as they occur:

int index = 0;for (id eachObject in array) {NSLog(@"Object at index %i is: %@", index, eachObject);index++;}

You cannot mutate a collection during fast enumeration, even if the collection is mutable. If you attempt to add or remove a collected object from within the loop, you’ll generate a runtime exception.

0 0
原创粉丝点击