NSMutableArray是NSArray对的子类,它是可变的,可以随意添加或者删除元素。与Array,也有静态和动态两种创建方法。也可已使用NSArray的方法来创建NSMutableArray。当一个元素被加到NSMutableArray中时,会执行一次retain操作;当一个元素从 NSMutableArray中删除时,会执行release操作;当集合被销毁时(调用了dealloc), NSMutableArray里的所有元素都会执行一次release操作(这个原则也适用于其他集合类型:NSDictionaryNSSet等)。
#import <Foundation/Foundation.h> @interface Student : NSObject @property (nonatomic, assign) int age; + (id)studentWithAge:(int)age; @end #import "Student.h" @implementation Student + (id)studentWithAge:(int)age { Student *stu = [[[Student alloc] init] autorelease]; stu.age = age; return stu; } - (void)dealloc { NSLog(@"[age=%i]被销毁了", _age); [super dealloc]; } @end
#import <Foundation/Foundation.h> #import "Student.h" void arrayCreate() { NSMutableArray *array = [NSMutableArray arrayWithObject:@"1"]; // 添加元素 [array addObject:@"2"]; [array addObject:@"3"]; // [array removeObject:@"2"]; // [array removeLastObject]; [array removeAllObjects]; NSLog(@"%@", array); } void arrayMemory() { NSMutableArray *array = [[NSMutableArray alloc] init]; // stu1:1 Student *stu1 = [[Student alloc] init]; stu1.age = 10; // stu2:1 Student *stu2 = [[Student alloc] init]; stu2.age = 20; // 对被添加的元素做一次retain操作,计数器+1 [array addObject:stu1]; // stu1:2 [array addObject:stu2]; // stu2:2 NSLog(@"add->stu1:%zi", [stu1 retainCount]); // 对被删除的元素做一次release操作,计数器-1 [array removeObject:stu1]; // stu1:1 NSLog(@"remove->stu1:%zi", [stu1 retainCount]); // 释放学生 [stu1 release]; // stu1:0 [stu2 release]; // stu2:1 // 当数组被释放的时候,会对所有的元素都做一次release操作 [array release]; // stu2:0 } void arrayReplace() { NSMutableArray *array = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil]; [array replaceObjectAtIndex:1 withObject:@"4"]; NSLog(@"%@", array); } void arraySort() { NSMutableArray *array = [NSMutableArray arrayWithObjects:@"1", @"3", @"2", nil]; [array sortUsingSelector:@selector(compare:)]; NSLog(@"%@", array); }