Nsmutablearray uses the enumeration method

Source: Internet
Author: User

You can also use the enumeration method for variable arrays. Here we provide two enumeration methods: positive enumeration, reverse enumeration, and positive enumeration, the number and sequence of elements cannot be modified, but can be modified in reverse enumeration. This is intriguing.

 

Methods involved:

Objectenumerator:Enumeration in positive order.

Reverseobjectenumerator:Inverted enumeration method.

 

Let's take a look at the example below:

//使用了枚举法的可变数组#import <Foundation/Foundation.h>int main(int argc, const char * argv[]) {    @autoreleasepool {        NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"One", @"Tow", @"Three", nil];        //objectEnumetator是一个正序枚举法.        //在使用正序枚举法的时候, 元素个数和元素顺序不允许修改.//        NSEnumerator *enumerator = [array objectEnumerator];//        NSString *str;//        int i = 0;//        while (str = [enumerator nextObject]){//            [array removeLastObject];//            NSLog(@"%d", i);//        }//        //reverseObjectEnumerator是一个逆序的枚举法.        //在逆序枚举法, 元素的个数和元素的顺序允许修改.        //PS:在逆序枚举法使用任何犯法去改变元素的个数或元素顺序都是可行的.        NSEnumerator *enumerator = [array reverseObjectEnumerator];        NSString *str;        while (str = [enumerator nextObject]) {            [array removeLastObject];            NSLog(@"%@", str);        }        //因为这里循环了3次, 每一次都会删除一个元素, 这样子就会导致输出来的结果是空的.        //2014-10-12 12:24:20.242 EnumNSMutableArray[881:303] ()                NSLog(@"%@", array);        [array release];    }    return 0;}

Output result:

2014-10-13 20:17:48.793 EnumNSMutableArray[6403:303] Three2014-10-13 20:17:48.794 EnumNSMutableArray[6403:303] Tow2014-10-13 20:17:48.794 EnumNSMutableArray[6403:303] One2014-10-13 20:17:48.795 EnumNSMutableArray[6403:303] ()Program ended with exit code: 0

 

Nsmutablearray uses the enumeration method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.