NSArray是Foundation框架中的不可变数组,我们来实现一下这些方法:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
//OC的数组可以存储不同类型的对象;OC的数组只能存储对象;
//但是内存空间还是连续的;
NSArray *arr1 = [[NSArray alloc] initWithObjects:@"1",@"2",@"3", nil];//数组最后一定要以nil结尾,表示数组结束;
NSLog(@"%@",arr1);
//计算数组长度;
int count = (int)arr1.count;
NSLog(@"count = %d",count);
//检测数组中是否有某个值;
BOOL isContainer = [arr1 containsObject:@"5"];
if (isContainer) {
NSLog(@"存在这个对象");
}else{
NSLog(@"不存在这个对象");
}
//获取最后一个对象;
NSString *lastObj = [arr1 lastObject];
NSLog(@"lastObj = %@",lastObj);
//获取第一个对象;
NSString *firstObj = [arr1 firstObject];
NSLog(@"firstObj = %@",firstObj);
//获取指定位置的对象;
NSString *indexObj = [arr1 objectAtIndex:2];
NSLog(@"indexObj = %@",indexObj);
//获取某个指定对象所在的位置;
//如果元素不存在,则打印-1;
int index = (int)[arr1 indexOfObject:@"2"];
NSLog(@"index = %d",index);
}
return 0;
}
输出结果如下:
.
github主页:https://github.com/chenyufeng1991 。欢迎大家访问!