1,创建数组对象
(1)使用便利构造器
arrayWithObjects 创建对象时可以指定多个对象,元素和元素之间通过逗号进行间隔.
nil 作为数组元素存放的结束标志,遇到nil 之后的元素,都不会放入数组.Next
arrayWithObjects:
Creates and returns an array containing the objects in the argument list.
+ (instancetype)arrayWithObjects:(id)firstObj,,...
(2)使用初始化
- (instancetype)initWithObjects:(id)firstObj,,...
2, 获取元素个数:count
Returns the number of objects currently in the array.
- (NSUInteger)count
3,根据索引获取对象
(1)获取指定下标对应的元素
objectAtIndex
Returns the object located at the specified index.
- (id)objectAtIndex:(NSUInteger)index
(2)获取数组中第一个元素: objectAtIndex:0或者是first object
frist object 与last object 方法比objectAtIndex:方法好在当数组元素为空时会返回nill而objectAtIndex:则会造成程序crash,index 0 beyond bound of empty array .数组下标越界.
(3)获取数组最后一个元素last object
4,获取对象在数组中的索引值: indexOfObject:@"cc"
数组中的元素们可以重复,而且重复的对象会成为数组元素(也就是能输出多个相同的元素)
5,判断是否包含某个对象:一个BOOL类型
BOOL isExist = [arr containsObject:@"Frank"];
6,数组排序(幼儿版)0.0 ...: sortedArrayUsingSelector:@selector(compare)
NSArray *per = [arr sortedArrayUsingSelector:@selector(compare)];
7,快速遍历,(快速枚举)
for( in )快速枚举也叫快速遍历
用于将集合中的元素遍历出来,for(type *object)() //type数组中对应的类型,object起一个对象的名字(自己拟定的)
collection :集合(也就是一个大容器,数组,字典,或者集合)(后面内容一般加上if语句进行判断)
NSMutableArray
1,先创建
初始化或者构造器创建几个对象
2,存储
定义一个存储空间用来存储创建好的对象,放进数组中
3,添加
先创建一个对象,之后用addobject: 方法进行操作就行了
4,删除
removeObject:
[arr removeObject:book];
5, 通过书名查找书本
for(Book *book in arr){
if([[book name] isEqualToString:@"牛逼比比比"])
{
//修改价格
[book setPrince:200];
NSLog(@"查找成功");
}
}
6,展示所有书名
for(Book *book in arr){
NSLog(@"%@",[book name]);
}
//删除removeObject
for (Book *b in arr) {
if ([[b name]isEqualToString:@"牛逼比比比"]) {
//删除
[arr removeObject:b];
}
}
报错uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x100202b00> was mutated while being enumerated.'
forin 在遍历的时候不可以被改变(移除),但是如果是最后一个元素的话,就不会出现.
解决方案:
1,Removes from the receiving array the objects in another given array.removeObjectsInArray:从接收数组中删除另一个给定的对象数组
2,for循环代替forin
3,查找要删除的元素下标,用数组存储下标,用forin循环依次删除
4,现将原数组逆序查找遍历,然后进行删除操作
NSNumber
1,将基本数据类型,转为NSNumber类型的对象
Creating an NSNumber Object
+ numberWithBool:
+ numberWithChar:
+ numberWithDouble:
+ numberWithFloat:
+ numberWithInt:
+ numberWithInteger:
+ numberWithLong:
+ numberWithLongLong:
+ numberWithShort:
+ numberWithUnsignedChar:
+ numberWithUnsignedInt:
+ numberWithUnsignedInteger:
+ numberWithUnsignedLong:
+ numberWithUnsignedLongLong:
+ numberWithUnsignedShort:
Initializing an NSNumber Object
– initWithBool:
– initWithChar:
– initWithDouble:
– initWithFloat:
– initWithInt:
– initWithInteger:
– initWithLong:
– initWithLongLong:
– initWithShort:
– initWithUnsignedChar:
– initWithUnsignedInt:
– initWithUnsignedInteger:
– initWithUnsignedLong:
– initWithUnsignedLongLong:
– initWithUnsignedShort:
2,将NSNumber类型的对象转为基本类型的对象
3,NSNumber 对象比较
[n1 compare n2];