您的位置:首页 > 其它

NSMutableArray和NSArray

2015-08-03 16:53 393 查看
//数组属于集合类型
#pragma mark ----------不可变数组
/*
1.oc中的数组只能存储对象类型
2.不能存储基本数据类型(int, NSInteger)
3.数组对象中可以同时存储不同类型的对象
4.数组元素是有序的,下标从0开始
5.nil是数组的结束标志
6.oc中数组越界,必然崩溃
7.如果是整体输出,有汉字的话,输出的Unicode编码,单独打印就不会出现这种情况
*/

//第一种创建方式
NSArray *array1 = [[NSArray alloc]initWithObjects:@"重庆",@"asdf", nil];
NSLog(@"%@",array1);

//第二种创建方式
NSArray *array2 = [NSArray arrayWithArray:array1];
NSLog(@"array2 = %@",array2);

//获取元素的个数
NSUInteger n = [array2 count];
NSLog(@"n = %lu",n);

//根据下标获取元素
NSLog(@"%@",[array2 objectAtIndex:1]);

//根据元素获取下标

NSLog(@"%lu",[array2 indexOfObject:@"重庆"]);

//语法糖,不需要nil结尾,只能使用在不可变的数组中
NSArray *array3 = @[@"1",@"2",@"3"];

//访问数组
NSLog(@"%@",array3[2]);

#pragma mark ---------------可变数组
//创建一个空得数组对象
NSMutableArray *marray = [NSMutableArray array];

NSLog(@"%@",marray);

NSMutableArray *marray2 = nil;
NSLog(@"marray2 = %@",marray2);

//添加
[marray addObject:@"hahah"];
[marray addObject:@"hahah"];
[marray addObject:@"hahah"];
[marray addObject:@"hahah"];
[marray addObject:@"hahah"];
[marray addObject:@"biubiubiu"];

NSLog(@"marray = %@",marray);

//插入
[marray insertObject:@"40" atIndex:0];
NSLog(@"marray = %@",marray);

//交换数组中元素的位置

[marray exchangeObjectAtIndex:1 withObjectAtIndex:2];
NSLog(@"marray = %@",marray);

//替换
[marray replaceObjectAtIndex:0 withObject:@"bengbeng"];
NSLog(@"marray = %@",marray);

//移除,把所有的相同的都删了

[marray removeObject:@"biubiu"];
NSLog(@"marray = %@",marray);
[marray removeLastObject];
NSLog(@"marray = %@",marray);
[marray removeObjectAtIndex:2];
[marray removeObject:@"hahah"];
NSLog(@"marray = %@",marray);
[marray removeAllObjects];
NSLog(@"marray = %@",marray);

Book *b1 = [Book bookWithName:@"数据结构" price:20.00];
Book *b2 = [Book bookWithName:@"计算机组成" price:23.00];
Book *b3 = [Book bookWithName:@"计算机网络" price:27.00];
Book *b4 = [Book bookWithName:@"深入内核" price:25.00];
Book *b5 = [Book bookWithName:@"网络管理" price:24.00];
Book *b6 = [Book bookWithName:@"网络安全" price:22.00];

NSMutableArray *libray = [NSMutableArray arrayWithObjects:b1,b2,b3,b4,b5,b6, nil];

NSString *searchName = @"网络管理";

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

Book *b  = libray[i];
if ([[b name] isEqualToString:searchName]) {
[b setPrice:50];
[b introduce];
}
}

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

Book *b  = libray[i];

[b introduce];

}

//添加一本书

Book *newbook = [Book bookWithName:@"资本论" price:99.99];

[libray addObject:newbook];

NSLog(@"%@",libray);

//删除书籍
[libray removeObject:@"数据结构"];
//        [libray removeObjectAtIndex:1];

#pragma mark ---------NSNumber NSValbe

//NSNumber 实现数值和对象的转换

NSNumber *number = [NSNumber numberWithInt:10];
NSLog(@"%@",number);

NSNumber *numb1 = [NSNumber numberWithFloat:19.99];
NSLog(@"%@",numb1);

float n1 = [numb1 floatValue];
NSLog(@"%.3f",n1);

//nsvalbe 实现结构体和对象的转换     nsvalue 是nsnumber的父类
NSRange range = NSMakeRange(1, 2);
NSValue *value = [NSValue valueWithRange:range];

}

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