obj-C有两种数组,一种是不可变数组NSArray(可以理解为常量),另一种是可变数组NSMutableArray。这里只说常用的NSMutableArray。对数组的操作有3个:插入、访问、删除。用 id array = [ [ NSMutableArray init ] alloc ]; [ array release ]; 来创建释放数组。数组长度可以通过 [ array count ]; 获得。
插入:[ array addObject:xxxxxxxx ];
访问:[ array objectAtIndex:下标 ];
删除:[ array removeObject:xxxxxxx ];
通过插入新节点的 addObject 方法,可以注意到add的只能是Object。如果是基本数据类型,那么就必须通过NSNumber转换一次了。
Creating an NSNumber Object
+ numberWithBool:
+ numberWithChar:
+ numberWithDouble:
+ numberWithFloat:
+ numberWithInt:
+ numberWithInteger:
+ numberWithLong:
+ numberWithLongLong:
+ numberWithShort:
+ numberWithUnsignedChar:
+ numberWithUnsignedInt:
+ numberWithUnsignedInteger:
+ numberWithUnsignedLong:
+ numberWithUnsignedLongLong:
+ numberWithUnsignedShort:
比如转换一个整形 id num = [ NSNumber numberWithInt:250 ]; 此对象就可以存入数组了。
取出来的时候依然需要转换一次。 int i = [ num intValue ];相对与上面用来封装的方法。下面是对应的解析方法
– boolValue
– charValue
– decimalValue
– doubleValue
– floatValue
– intValue
– integerValue
– longLongValue
– longValue
– shortValue
– unsignedCharValue
– unsignedIntegerValue
– unsignedIntValue
– unsignedLongLongValue
– unsignedLongValue
– unsignedShortValue
Objective-C数组相关操作。
// insert code here...
NSLog(@"数组");
//指定多个字符串创建数组
NSArray *array;
array=[NSArray arrayWithObjects:@"0-asd",@"1-fds",@"2-哈咯",@"3-个人",nil];
//数组的长度
NSLog(@"数组长度%d",array.count);
//通过索引取得对象
for(int i=0;i<array.count;i++)
{
NSString *secondStr=[array objectAtIndex:i];
NSLog(secondStr,nil);
}
//高速枚举法取得对象,Objective-C2.0开始支持,
for(NSString *str in array)
{
NSLog(str,nil);
}
//对象的追加于删除
//创建空数组
NSMutableArray *MutArray=[NSMutableArray array];
//追加对象
[MutArray addObject:@"A"];
[MutArray addObjectsFromArray:array];
//插入对象
NSString *thstr=@"插入值";
[MutArray insertObject:thstr atIndex:4];
//替换对象
[MutArray replaceObjectAtIndex:2 withObject:@"替换"];
//删除所有对象
//[Mutarray removeAllObjects];
//删除最后的对象
[MutArray removeLastObject];
//删除索引为Index的对象
[MutArray removeObjectAtIndex:0];
//删除所有于object同值的对象
[MutArray removeObject:@"0-asd"];
//删除数组中所有与object等价的对象
[MutArray removeObjectIdenticalTo:thstr];
//删除数组中所有与数组array包含相同的元素
[MutArray removeObjectsInArray:array];
NSLog(@"%@",MutArray);