// // main.m // NSArray是不可变的,一旦初始化完毕,就不能添加和删除了。类似于NSString和NSMutilString。 #import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { NSArray *arr1 = [[NSArray alloc] init]; //NSArray是不可变的,这样创建空的数组,以后又不能修改,所以这是没用的。 NSArray *arr2 = [NSArray arrayWithObject:@"lnj"]; // 数组中的nil是结束符 NSArray *arr3 = [NSArray arrayWithObjects:@"lnj", @"lmj" ,@"jjj", @"cp", nil]; NSLog(@"%@", arr3);//(lnj,lmj,jjj,cp),圆括号就是数组。 Person *p = [Person new]; NSObject *obj = [NSObject new]; //+ (instancetype)arrayWithObjects:(ObjectType)firstObj, ... NS_REQUIRES_NIL_TERMINATION; ...表示是可变参数。 NSArray *arr4 = [NSArray arrayWithObjects:p, obj, @"lnj", nil];//nil是一个结束符 NSLog(@"arr = %@", arr4);//("<Person: 0x100304790>","<NSObject: 0x1007003b0>",lnj) NSLog(@"count = %lu", [arr4 count]);//3 NSLog(@"last = %@", [arr4 lastObject]);//lnj NSLog(@"first = %@", [arr4 firstObject]);//<Person: 0x100304790> NSLog(@"arr[1] = %@", [arr4 objectAtIndex:1]);//<NSObject: 0x1007003b0> NSArray *arr5 = [NSArray arrayWithObjects:@"lnj", @"lmj", @"jjj", @"zs", nil]; if([arr5 containsObject:@"zs"]) { NSLog(@"arr中包含zs"); }else { NSLog(@"arr中不包含zs"); } // 创建数组简写 NSString *str = @"lnj"; NSArray *arr6 = [NSArray arrayWithObjects:@"lnj", @"lmj", @"jjj", nil]; NSArray *arr7 = @[@"lnj", @"lmj", @"jjj"]; // 获取数组元素的简写 NSLog(@"%@", [arr7 objectAtIndex:0]); NSLog(@"%@", arr7[0]); return 0; }