您的位置:首页 > 其它

数组

2015-07-18 09:06 239 查看
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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: