您的位置:首页 > 其它

个人整理--OC中的数组

2015-07-23 22:04 267 查看
//OC中的数组存放的一定是对象
NSArray *arr = [[NSArray alloc]init];
//用便利构造器的方式创建一个空数组
NSArray *arr = [NSArray array];
//字面量的方式
NSArray *arr = @[@"1",@"2",@"3",@"4",@"5"];
//.count:能够读出数组中元素个数.
NSLog(@"%ld",arr.count);
//取值也是通过下标进行取值,返回的是一个对象;
NSLog(@"%@",[arr objectAtIndex:1]);
NSLog(@"%@",arr[1]);
//for 对数组进行遍历
for (NSInteger i = 0 ; i < arr.count ; i ++){
NSLog(@"%@",arr[i]);
}
NSLog(@"%@",[arr containsObject:@"6"]);


Student *stu1 = [[Student alloc]initWithName:@"刘鑫奇"];
Student *stu2 = [[Student alloc]initWithName:@"高薪茹"];
Student *stu3 = [[Student alloc]initWithName:@"高小妖精"];
Student *stu4 = [[Student alloc]initWithName:@"高大贱人"];
NSArray *arr = [[NSArray alloc]initWithObjects:stu1,stu2,stu3,stu4, nil];
//用便利构造器的方式创建
NSArray *arr = [NSArray arrayWithObjects:stu1,stu2,stu3,stu4,nil];
//快速枚举:能快速的遍历数组等容器对象
//都是对容器中的每一个元素的遍历
//为了增加代码的阅读性,避免不必要的错误,尽量让 forin的前部分的类型和数组里元素类型相同
for (NSString *str in arr) {
NSLog(@"%@",str);
}
NSArray *arr1 = @[@"刘鑫奇",@"刘山山",@"刘星宇",@"刘能"];
NSArray *arr2 = @[@"腾飞",@"周胜民",@"商帅",@"郭洪瑞"];
NSArray *arr = @[arr1 , arr2];
//对arr进行forin遍历
for (NSArray *temp in arr){
for (NSString *str in temp){
NSLog( @"%@",str);
}
}
Student *stu1 = [[Student alloc]initWithName:@"刘鑫奇"];
Student *stu2 = [[Student alloc]initWithName:@"高薪茹"];
Student *stu3 = [[Student alloc]initWithName:@"高小妖精"];
Student *stu4 = [[Student alloc]initWithName:@"高大贱人"];
NSArray *arr1 = @[stu1,stu2,stu3];
NSArray *arr2 = @[stu4];
NSArray *arr = @[arr1 , arr2];
//遍历数组里每一个学生的姓名
for (Student *temp in arr) {
for (Student *stu in temp) {
NSLog(@"%@",stu.name);
}
}


//可变数组
NSMutableArray *arr = [[NSMutableArray alloc]init];
NSMutableArray *arr1 = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4", nil];
//添加一个字符串
//添加到数组的最后一位
[arr addObject:@"8"];
NSLog(@"%@",arr);
//移除下标2的字符串
[arr removeObjectAtIndex:2];
NSLog(@"%@",arr);
//替换一个字符串
[arr replaceObjectsAtIndexes:1 withObject:@"7"];
NSLog(@"%@",arr);
//交换两个字符串
[arr exchangeObjectAtIndex:1 withObjectAtIndex:4];
NSLog(@"替换%@",arr);
//清空数组
[arr removeAllObjects];
NSLog(@"清空%@",arr);


Book *book1 = [Book bookWithbookName:@"西游记" bookPrice:30];
Book *book2 = [Book bookWithbookName:@"水浒传" bookPrice:25];
Book *book3 = [Book bookWithbookName:@"三国演义" bookPrice:35];
Book *book4 = [Book bookWithbookName:@"金瓶梅(插图版)" bookPrice:40];
//四本书放在一个可变数组中
NSMutableArray *bookArr = [NSMutableArray arrayWithObjects:book1,book2,book3,book4, nil];
//    2、数组可以添加、删除书籍。
Book *book5 = [Book bookWithbookName:@"红楼梦" bookPrice:38];
[bookArr addObject:book5];
for (Book *book in bookArr) {
NSLog(@"%@ , %ld",book.bookName,book.bookPrice);
}
[bookArr removeObject:book5];
for (Book *book0 in bookArr) {
NSLog(@"%@ ,%ld ",book0.bookName , book0.bookPrice);
}
for (Book *temp in bookArr) {
if ([temp.bookName isEqualToString:@"红楼梦"]) {
temp.bookPrice = 150;
}
}
for (Book *temp in bookArr) {
NSLog(@"%@,%ld",temp.bookName,temp.bookPrice);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: