NSArray和NSMutableArray

1.不可变数组(NSArray)的操作

   1.1.不可变数组的声明,不可变数组生命有很多方式,这里只有最基本的一种

// 声明一个数组
// 数组的元素可以是任意的对象
// 数组中装的是对象的地址
NSArray * array = [[[NSArray alloc] initWithObjects:@"one",@"two",@"three", nil] autorelease];

 1.2.直接打印数组,会将数组的元素都打印出来

// 声明一个数组
// 数组的元素可以是任意的对象
// 数组中装的是对象的地址
NSArray * array = [[[NSArray alloc] initWithObjects:@"one",@"two",@"three", nil] autorelease];
        
// 数组的遍历
// 直接打印数组的时候,会将数组的每个元素都打印出来,在数组类中重写了description方法,%@打印对象,就会获得description方法的返回值
NSLog(@"my array is %@",array);

 1.3.数组的遍历

        1.3.1.枚举器法遍历数组

NSEnumerator * enumerator = [array objectEnumerator];
id obj;
while(obj = [enumerator nextObject]){
      NSLog(@"枚举器法进行数组的遍历:%@",obj);
}

    1.3.2.foreach遍历

for(id obj in array){
      NSLog(@"foreach遍历数组元素是 :%@",obj);
}

    1.3.3.for遍历

for(int i = 0; i < [array count];i++){
      NSLog(@"for方法返回的数组元素是:%@",[array objectAtIndex:i]);
}

2.可变数组(NSMutableArray)的操作,可变数组是不可变数组的子类,所以可变数组可以使用不可变数组的方法

   2.1.向可变数组中添加元素

NSMutableArray *mutableArray = [[[NSMutableArray alloc] init] autorelease];
[mutableArray addObject:@"haha"];
[mutableArray addObject:@"hoho"];
[mutableArray addObject:@"nienie"];
NSLog(@"mutableArray is %@",mutableArray);

 2.2.删除元素 使用remove的一系列方法

[mutableArray removeObject:@"hoho"]; // 根据内容删除数组对象
[mutableArray removeObjectAtIndex:0]; // 根据数组下标删除对象
NSLog(@"删除后mutableArray is %@",mutableArray);

   2.3.交换两个数组元素的位置

[mutableArray exchangeObjectAtIndex:0 withObjectAtIndex:1];
NSLog(@"交换位置后的mutableArray is %@",mutableArray);

 2.4.可变数组的遍历,其他和NSArray一致

        2.4.1.在枚举器法正序遍历和foreach方法遍历数组中,不能去改变这个数组中元素的值,但是在可变数组的逆序遍历中可以修改可变数组中的元素

NSMutableArray  *testMutableAray = [[[NSMutableArray alloc] init] autorelease];
[testMutableAray addObject:@"张三"];
[testMutableAray addObject:@"李四"];
[testMutableAray addObject:@"王五"];
[testMutableAray addObject:@"赵六"];

 NSEnumerator * myenumerator = [testMutableAray reverseObjectEnumerator];
        NSString *str;
 while (str = [myenumerator nextObject]) {
      [testMutableAray removeLastObject];
}
NSLog(@"%@",testMutableAray);

   3.字符串和数组之间的转化

        3.1.将字符串分割成数组

NSString * mySubstr = @"I am a poor man";
NSLog(@"原始的字符串是:%@",mySubstr);
NSArray * mySubArray = [mySubstr componentsSeparatedByString:@" "];
NSLog(@"分割后的数组是:%@",mySubArray);

     3.2.将数组拼接成字符串

// 将数组拼接成字符串
// 方法1.
NSEnumerator * mySubEnumerator = [mySubArray reverseObjectEnumerator];
NSMutableArray * subMutableArray = [[[NSMutableArray alloc] init] autorelease];
id subObj;
while (subObj = [mySubEnumerator nextObject]) {
     [subMutableArray addObject:subObj];
     NSLog(@"逆序后遍历的字符串是:%@",subObj);
}

// 方法2        
// componentsJoinedByString后面的“--”是字符串之间的连接符
NSString * joinedStr = [subMutableArray componentsJoinedByString:@"--"];
NSLog(@"拼接之后生成的新的数组是:%@",joinedStr);

  

原文地址:https://www.cnblogs.com/zwhFighting/p/4550783.html