数组

1. 数组分为可变数组和不可变数组.

不可变数组 : 一旦定义就不可再改变

可变数组 : 可以进行增删改等操作.


2. 数组的常见用法 .

NSMutableArray *array2 = [NSMutableArray array];
(1) 添加元素
   [array2 addObject:indenStr];
(2) 删除元素
    [array2 removeObjectAtIndex:2];
(3) 插入元素
    [array2 insertObject:@"聊李飞" atIndex:4];
(4) 替换元素
    [array2 replaceObjectAtIndex:3 withObject:@"9"];
(5) 获取第一个元素
    NSString *str3 = [array2 firstObject];
(6) 获取最后一个元素
    NSString *str4 = [array2 lastObject];
(7) 删除所有元素.
    [array2 removeAllObjects];


3. 数组使用时需要注意的问题

(1) 数组内存的是对象 . NSInteger , int , BOOL 都是基本类型 , 不能存入数组中并且是有序的 .

(2) 数组通过下标取出元素 . 

NSArray *array = [NSArray arrayWithObjects:@"张三",@"李四",@"王五",@"赵六", nil];

<pre name="code" class="objc">NSString *name2 = [array objectAtIndex:1];//取出数组中的某个元素根据数组下标获取

 

(3) 用for循环循环遍历数组的时候,对数组中某个元素进行删除 , 会影响循环条件,多以必须要创建一个同样的数组进行遍历 , 对另一个数组进行删除 . 具体实例如下:

 

Student *stu1 = [[Student alloc] init];
    stu1.name = @"账单";
    stu1.age = 23;
    stu1.sex = @"男";
    Student *stu2 = [[Student alloc] init];
    stu2.name = @"王五";
    stu2.age = 27;
    stu2.sex = @"男";
    Student *stu3 = [[Student alloc] init];
    stu3.name = @"李四";
    stu3.age = 21;
    stu3.sex = @"女";
    Student *stu4 = [[Student alloc] init];
    stu4.name = @"小梅";
    stu4.age = 28;
    stu4.sex = @"女";
    Student *stu5 = [[Student alloc] init];
    stu5.name = @"小强";
    stu5.age = 29;
    stu5.sex = @"男”;
NSMutableArray *array = [NSMutableArray arrayWithObjects:stu1,stu2,stu3,stu4,stu5,nil];
    NSMutableArray *array1 = [NSMutableArray arrayWithArray:array];

    for (int i = 0; i < [array count]; i++) {
        
        //*****注意*****循环遍历数组的时候,对数组中的某个元素进行删除会影响循环条件,导致数组不正确,所以必须要创建一个同样地数组进行遍历,对另一个数组进行删除
        
        Student *stu = [array objectAtIndex:i];
        
        if (stu.age > 26) {
            
            [array1 removeObject:stu];
            
            NSLog(@"name = %@ age = %ld sex = %@",stu.name,stu.age,stu.sex);
        }
        
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值