操纵数组内容(Objective-C 开发范例)

来源:互联网 发布:北大燕京学堂知乎 编辑:程序博客网 时间:2024/05/17 08:18

操纵数组内容(NSMutableArray)

问题

      你希望数组内容能够更具动态性,这样用户或你就可以在数组中添加、删除和插入对象了。然而,NSArray 是不可变类,因此一旦创建NSArray 对象,你就无法再对其中内容进行任何修改。
解决方案
       如果你认为所用的数组需要是动态的,那么请使用NSMutableArray。NSMutableArray是NSArray的子类,这样就可以像NSArray那样使用NSMutableArray了。但NSMutableArray提供了额外的一些方法,可以通过这些方法在数组列表中添加、删除和插入对象。
说明

      首先实例化NSMutableArray 类,可以使用任何构造函数进行实例化。要想创建新的空的NSMutableArray 对象,只需要使用alloc 与init 即可:

NSMutableArray *listOfLetters = [[NSMutableArray alloc] init];
      要想向数组中添加对象,需要向数组发送addObject:消息并且将想要添加到数组中的对象作为参数传递进去:
[listOfLetters addObject:@"A"];[listOfLetters addObject:@"B"];[listOfLetters addObject:@"C"];
       在使用addObject:时,总是会将对象添加到数组列表的末尾。如果想要将对象插入到数组中的其他位置,那么需要使用insertObject:atIndex:方法:
[listOfLetters insertObject:@"a"                    atIndex:0];
       这会将对象插入到数组的首个位置。
       如果想要将某个索引位置的对象替换为另一个对象,那么可以使用replaceObjectAtIndex:withObject:方法。下面的代码展示了如何将字符C 替换为小写字母c:

[listOfLetters replaceObjectAtIndex:2                         withObject:@"c"];
     要想交换数组中两个对象的位置,可以使用exchangeObjectAtIndex:withObjectAtIndex:方法:
[listOfLetters exchangeObjectAtIndex:0                   withObjectAtIndex:2];
     当需要删除数组中的对象时,可以选择几种不同的方法。可以删除特定索引位置的对象,可以删除数组中的最后一个对象,还可以删除列表中的全部对象。如果拥有某个对象的引用,那么还可以通过对象引用删除数组中的这个对象。如下代码展示了删除对象的各种方式:

[listOfLetters removeObject:@"A"];[listOfLetters removeObjectAtIndex:1];[listOfLetters removeLastObject];[listOfLetters removeAllObjects];

代码
程序清单main.m

#import <Foundation/Foundation.h>int main (int argc, const char * argv[]){     @autoreleasepool {     NSMutableArray *listOfLetters = [[NSMutableArray alloc] init];     [listOfLetters addObject:@"A"];     [listOfLetters addObject:@"B"];     [listOfLetters addObject:@"C"];     NSLog(@"OBJECTS ADDED TO ARRAY: %@", listOfLetters);     [listOfLetters insertObject:@"a"                         atIndex:0];     NSLog(@"OBJECT 'a' INSERTED INTO ARRAY: %@", listOfLetters);     [listOfLetters replaceObjectAtIndex:2                              withObject:@"c"];     NSLog(@"OBJECT 'c' REPLACED 'C' IN ARRAY: %@", listOfLetters);     [listOfLetters exchangeObjectAtIndex:0                        withObjectAtIndex:2];     NSLog(@"OBJECT AT INDEX 1 EXCHANGED WITH OBJECT AT INDEX 2 IN ARRAY:%@", listOfLetters);     [listOfLetters removeObject:@"A"];     NSLog(@"OBJECT 'A' REMOVED IN ARRAY: %@", listOfLetters);     [listOfLetters removeObjectAtIndex:1];     NSLog(@"OBJECT AT INDEX 1 REMOVED IN ARRAY: %@", listOfLetters);     [listOfLetters removeLastObject];     NSLog(@"LAST OBJECT REMOVED IN ARRAY: %@", listOfLetters);     [listOfLetters removeAllObjects];     NSLog(@"ALL OBJECTS REMOVED IN ARRAY: %@", listOfLetters);    }    return 0;}


阅读全文
0 0
原创粉丝点击