Object-C语言数组的创建和应用【入门】

OC是iOS开发中专门的一种语言

数组:不可变数组NSArray、可变数组NSMutableArray

一、不可变数组:
1、创建不可变数组:
(1)类方法创建:

NSArray *array = [NSArray arrayWithObjects:@"object1",@"object2",@"object3",nil];
//输出NSLog(@"%@",array);

输出:(object1,
object2,
object3)
(2)实例化方法创建:

NSArray *array_1 = [[NSArray alloc] initWithObjects:@"one",@"two",@"three",nil];

输出:(one,
two,
three)
(3)创建空数组:

NSArray *array2 = [NSArray array];
NSArray *array1 = [[NSArray alloc]init];

(4)根据已有数组创建新数组(类似复制);

NSArray *copyArray = [NSArray arrayWithArray:array];

(5)向数组尾部添加一个元素

NSArray *morearray = [array arrayByAddingObject:@"object4"];

(6)分隔符拼接数组,类似Java的split:
数组转成字符串输出

NSArray *array = [NSArray arrayWithObjects:@"object1",@"object2",@"object3",nil];
NSLog(@"%@",[array componentsJoinedByString:@","]);

字符串转数组:

NSString *string = @"1,2,3,4,5,6,7,8,9";
NSArray *sarr = [string componentsSeparatedByString:@","];

输出:object1,object2,object3
(7)判断数组是否包含某个对象,containsObject:

NSString *str = [NSString stringWithFormat:@"android"];
if([array containsObject:str]){
        NSLog(@"包含%@",str);
}else{
        NSLog(@"不包含%@",str);
}

(8)返回数组大小:

NSArray *array = [NSArray arrayWithObjects:@"1",@"2",@"3",nil];
NSInteger arraycount = [array count];

输出:3
(9)返回某个数组下标值:

NSInteger indexInArray = [array indexOfObject:@"2"];

二、可变数组:

(1)创建空数组:

NSMutableArray *emptyArray = [[NSMutableArray alloc]init];//空数组

(2)实例化创建数组:

NSMutableArray *mutarray = [NSMutableArray arrayWithObjects:@"one",@"a",@"two",@"b",@"b",@"b",@"three",@"b",@"four", nil];

(3)数组的排序:
1,循环添加并排序的方式:

NSArray *oldarray = [NSArray arrayWithObjects:@"b",@"a",@"e",@"d",@"c",@"f",@"h",@"g",nil];
for(id obj in oldarray){
       newArray addObject:obj];//将元素添加到数组newArray
       [newArray sortUsingSelector:@selector(compare:)];//将已添加的数组排序
       //NSLog(@"newArray:%@",newArray);
}

2、直接将数组排序:

NSArray *oldarray = [NSArray arrayWithObjects:@"b",@"a",@"e",@"d",@"c",@"f",@"h",@"g",nil];
NSArray *newArray1 = [oldarray sortedArrayUsingSelector:@selector(compare:)];

(4)预先开辟可变数组的长度initWithCapacity:

NSMutableArray *emptyarray = [[NSMutableArray alloc] initWithCapacity:0];//initWithCapacity预先开辟容量:0

(5)删除数组元素:
1、删除最后一个元素;

[array removeLastObject];

2、删除指定元素:

[mutarray removeObject:@"object1"];

3、删除范围内的元素(包括边界):
mutarray

NSRange range = NSMakeRange(2, 4);//包括边界
[mutarray removeObject:@"b" inRange:range];

4、删除指定下标的元素:

[mutarray removeObjectsAtIndexes:2];

你可能感兴趣的:(iOS,ios,objective-c,开发语言)