NSArray的具体使用情况,请见代码:
#import
int main(int argc, const char * argv[])
{
@autoreleasepool {
//类方法数组创建
NSArray *array1 = [NSArray arrayWithObject:@"obj"];
NSArray *array2 = [NSArray arrayWithObjects:@"obj1", @"obj2", @"obj3", nil];
NSArray *array3 = [NSArray arrayWithArray:array2];
NSLog(@"array1 :%@", array1);
NSLog(@"array2 :%@", array2);
NSLog(@"array3 :%@", array3);
//实例方法创建数组
NSArray *array4 = [[NSArray alloc] initWithObjects:@"AAA", @"bbb", nil];
NSLog(@"array4 :%@", array4);
//数组个数
NSLog(@"array3 count :%lu", [array3 count]);
//访问元素
NSLog(@"obj at index :%@", [array2 objectAtIndex:2]);
//追加(返回新的array对象)
NSArray *array5 = [array3 arrayByAddingObject:@"ccc"];
NSLog(@"array5 :%@", array5);
//根据指定的字符串连接数组元素
NSString *joinString1 = [array5 componentsJoinedByString:@"|"];
NSLog(@"joinString :%@",joinString1);
//是否包含指定对象
NSLog(@"isContains :%d", [array5 containsObject:@"obj2"]);
//查找某个对象所在索引
NSLog(@"indexOfObject :%lu",[array5 indexOfObject:@"obj3"]);
//最后一个元素
NSLog(@"lastObejct :%@", [array5 lastObject]);
//遍历数组
for (id element in array5) {
NSLog(@"element :%@", element);
}
//可变数组(期望容量设置为3)
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:3];
//直接添加
[mutableArray addObject:@"aaa"];
[mutableArray addObject:@"eee"];
[mutableArray addObject:@"000"];
NSLog(@"addObject :%@", mutableArray);
//插入元素
[mutableArray insertObject:@"ccc" atIndex:0];
NSLog(@"insertObject :%@", mutableArray);
//移除指定元素
[mutableArray removeObject:@"ccc"];
NSLog(@"removeObject :%@", mutableArray);
//移除指定下标元素
[mutableArray removeObjectAtIndex:0];
NSLog(@"removeObjectAtIndex :%@", mutableArray);
//移除最后一个元素
[mutableArray removeLastObject];
NSLog(@"removeLastObject :%@", mutableArray);
//添加数组
[mutableArray addObjectsFromArray:array5];
NSLog(@"addObjectsFromArray :%@", mutableArray);
//移除指定数组中的内容
[mutableArray removeObjectsInArray:array2];
NSLog(@"removeObjectsInArray :%@", mutableArray);
//指定索引替换对象
[mutableArray replaceObjectAtIndex:0 withObject:@"==="];
NSLog(@"replaceObjectAtIndex :%@", mutableArray);
//删除全部对象
[mutableArray removeAllObjects];
NSLog(@"removeAllObjects :%@", mutableArray);
}
return 0;
}
代码已经写的很清楚,这里需要特别注意的是:
NSLog(@"array3 count :%lu", [array3count]);
NSLog(@"indexOfObject :%lu",[array5indexOfObject:@"obj3"]);
这两个地方时需要用%lu的,而不是%d其实学习一门语言没有其他途径,就是需要平时自己慢慢积累,找资料,找案例的。