IOS OC NSArray&NSMutableArray


          /* 数组基础知识 */

        //创建一个数组

        NSArray *arr1=[[NSArray alloc] initWithObjects:@"1",@"2",@"3", nil];

        NSArray *arr2=[[NSArray alloc] initWithArray:arr1];

        

        //获取数组长度

        NSInteger count=arr1.count;

        

        /* 数组的遍历 */

        

        //1.for循环输出

        for (int i=0; i<arr1.count; i++) {

            NSLog(@"%@",arr1[i]);

        }

        //快速遍历

        for (id obj in arr1) {

            NSLog(@"%@",obj);

        }

        //枚举遍历

        NSEnumerator *enumerator=[arr1 objectEnumerator];

        id obj;

        while(obj=[enumerator nextObject]) {

            NSLog(@"%@",obj);

        }

        

        /* 可变数组 */

        

        // 创建一个可变数组

        NSMutableArray *arrayM = [[NSMutableArray alloc] init];

        

        // 添加数据

        [arrayM setArray:@[@"3",@"8",@"6"]];

        

        // 增加元素

        [arrayM addObject:@"9"];

        

        // 插入元素

        [arrayM insertObject:@"0" atIndex:2];

        

        // 删除元素

        [arrayM removeObject:@"0"];

        [arrayM removeObjectAtIndex:2];

        

        // 交换元素的位置

        [arrayM exchangeObjectAtIndex:1 withObjectAtIndex:2];

        NSLog(@"%@",arrayM);

        

        /* 数组元素排序 */

        NSMutableArray *arrM=[[NSMutableArray alloc] initWithArray:arrayM];

        for (int i=0; i<arrM.count-1; i++) {

            for (int j=i+1; j<arrM.count; j++) {

                NSComparisonResult result=[arrM[i] compare:arrM[j]];

                if (result==NSOrderedAscending) {

                    [arrM exchangeObjectAtIndex:i withObjectAtIndex:j];

                }

            }

        }

        NSLog(@"%@",arrM);

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/yuqingzhude/p/4836549.html