1.介绍
NSArray:是一个不可变数组。
使用过程注意:
不能存放非oc类型,如int,double,enum。
NSMutableArray:NSArray的字类,数组可变。
2.使用介绍
1.实例化
//创建一个空的array
NSArray *array1=[NSArray array];
//创建含一个对象的数组
NSArray *array2=[NSArray arrayWithObject:@"hello"];
//创建含多个对象的数组时要以nil结尾
NSArray *array3=[NSArray arrayWithObjects:@"hello",@"world", nil];
//快速创建
NSArray *array4=@[@"hello",@"world"];
NSMutableArray *marray1=[NSMutableArray array];
NSMutableArray *marray2=[NSMutableArray arrayWithArray:array3];
2.NSMutableArray的增加和删除对象
NSMutableArray *marray1=[NSMutableArray array];
//增加对象
[marray1 addObject:@"hello"];
//删除对象
[marray1 removeObjectAtIndex:0];
3. NSArray的遍历
NSArray *array = @[@"hello", @"world", @"!"];
//第一种便利 for
for (int i = 0; i<array.count; i++)
{
NSLog(@"%@", array[i]);
}
//id obj代表着数组中的每一个元素
//in 遍历
int i = 0;
for (id obj in array)
{
// 找出obj元素在数组中的位置
NSUInteger i = [array indexOfObject:obj];
NSLog(@"%ld %@", i, obj);
}
//枚举遍历
[array enumerateObjectsUsingBlock:
// 每遍历到一个元素,就会调用一次block
// 并且当前元素和索引位置当做参数传给block
^(id obj, NSUInteger idx, BOOL *stop)
{
NSLog(@"%ld %@", idx, obj);
if (idx == 2)
{
// 停止遍历
*stop = YES;
}
}];
3.复杂操作
Student *s1=[[Student alloc] initname:@"aaa" age:18 score:99];
Student *s2=[[Student alloc] initname:@"bbb" age:19 score:99];
Student *s3=[[Student alloc] initname:@"ccc" age:18 score:99];
Student *s4=[[Student alloc] initname:@"ddd" age:18 score:100];
Student *s5=[[Student alloc] initname:@"eee" age:20 score:99];
//临时变量
Student *stu1,*stu2;
NSMutableArray *stuArray=[NSMutableArray arrayWithObjects:s1,s2,s3,s4,s5,nil];
for (int i=0; i<stuArray.count; i++) {
for (int j=0; j<stuArray.count-i-1; j++) {
stu1=[stuArray objectAtIndex:j];
stu2=[stuArray objectAtIndex:j+1];
//先按照成绩排序
if (stu1.score<stu2.score) {
[stuArray replaceObjectAtIndex:j withObject:stu2];
[stuArray replaceObjectAtIndex:j+1 withObject:stu1];
}
}
}
//按照年龄排序
for (int i=0; i<stuArray.count; i++) {
for (int j=0; j<stuArray.count-i-1; j++) {
stu1=[stuArray objectAtIndex:j];
stu2=[stuArray objectAtIndex:j+1];
//如果两个学生的成绩相等则比较他们的年纪再来排序
if (stu1.score==stu2.score) {
if(stu1.age<stu2.age){
[stuArray replaceObjectAtIndex:j withObject:stu2];
[stuArray replaceObjectAtIndex:j+1 withObject:stu1];
}
}
}
}
//按照名称来排序
for (int i=0; i<stuArray.count; i++) {
for (int j=0; j<stuArray.count-i-1; j++) {
stu1=[stuArray objectAtIndex:j];
stu2=[stuArray objectAtIndex:j+1];
//如果两个学生的年龄相等则比较他们的名称再来排序
if (stu1.age==stu2.age) {
if ([stu1.name compare:stu2.name]<0) {
[stuArray replaceObjectAtIndex:j withObject:stu2];
[stuArray replaceObjectAtIndex:j+1 withObject:stu1];
}
}
}
}
for (int i=0; i<stuArray.count; i++) {
[[stuArray objectAtIndex:i] input];
}