我们可以通过多种方式去操作NSArray对象,比如让某个对象的实例变量指向这个数组,将该数组当做参数传给某一个方法或者函数,获取数组中对象个数,提取某一个对象、查找数组中的对象,遍历数组……
NSArray类有两个限制:
①它只能存储Objective-C对象,而不能存储C语言中的基础数据类型,比如int、float、enum、struct和NSArray中的随机指针。
②不能在NSArray中存放nil(对象的零值或者NULL值)。
创建NSArray的方法:
//通过类方法arrayWithObjects:创建,nil代表结束。 NSArray *array = [NSArray arrayWithObjects:@"red",@"yellow",@"blue",nil]; //使用数组字面量格式创建数组 NSArray *array2 = @[@"red",@"yellow",@"blue"];
Array的基本用法:
#import int main(int argc, char *argv[]) { @autoreleasepool { NSObject *obj = [[NSObject alloc]init]; NSArray *array = @[@"red",@"yellow",@"blue",obj]; //[array count]:数组的长度 NSLog(@"array Count:%lu",[array count]); //遍历数组 for (NSObject *object in array) { NSLog(@"array数组的对象:%@", object); } //[array objectAtIndex:2]:传入数组脚标的id获取数组对象 NSLog(@"Index 2:%@", [array objectAtIndex:2]); } return 0; }输出:
2017-05-05 02:01:37.363 test.out[7883:5345136] array Count:4
2017-05-05 02:01:37.364 test.out[7883:5345136] array数组的对象:red
2017-05-05 02:01:37.364 test.out[7883:5345136] array数组的对象:yellow
2017-05-05 02:01:37.364 test.out[7883:5345136] array数组的对象:blue
2017-05-05 02:01:37.364 test.out[7883:5345136] array数组的对象:<NSObject: 0x7fb144401e70>
2017-05-05 02:01:37.364 test.out[7883:5345136] Index 2:blue
使用-componentsSeparatedByString:切分数组
使用componentJoinByString:合并数组并创建字符串
NSString *string = @"red:yellow:blue";
//将string分成一个有三个对象的数组,对象分别为red、yellow、blue
NSArray *array = [string componentsSeparatedByString:@":"];
//将array合并成一个string,创建一个内容为red||yellow||blue的字符串
string = [array componentsJoinedByString:@"||"];
NSMutableArray是可变数组,可以随意添加或者删除数组中的对象。
创建NSMutable的方法:+(id) arrayWithCapacity: (NSUInteger) numItems;
这里数组容量只是一个参考值。容量数值之所以存在,是为了让Cocoa能够对代码进行一些优化。Cocoa既不会将对象预写入数组中,也不会用该容量去限制数组的大小。
NSMutableArray *array = [NSMutableArray arrayWithCapacity:10];
在数组末尾添加对象:-(void) addObject:(id)anObject;
删除特定索引处的对象:-(void) removeObjectAtIndex: (NSUInteger) index;
举例:
#import int main(int argc, char *argv[]) { @autoreleasepool { NSMutableArray *array1 = [NSMutableArray arrayWithCapacity:20]; array1 = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil]; //在数组末尾添加对象 [array1 addObject:@"Four"]; NSLog(@"array:%@",array1); //输出特定索引处的对象 [array1 removeObjectAtIndex:1]; NSLog(@"array:%@",array1); } return 0; }输出:
2017-05-05 02:10:21.197 test.out[8141:5349877] array:(
One,
Two,
Three,
Four
)
2017-05-05 02:10:21.197 test.out[8141:5349877] array:(
One,
Three,
Four
)