Objective-C:Foundation框架-常用类-NSMutableArray

  NSMutableArray是NSArray对的子类,它是可变的,可以随意添加或者删除元素。与Array,也有静态和动态两种创建方法。也可已使用NSArray的方法来创建NSMutableArray。当一个元素被加到NSMutableArray中时,会执行一次retain操作;当一个元素从 NSMutableArray中删除时,会执行release操作;当集合被销毁时(调用了dealloc), NSMutableArray里的所有元素都会执行一次release操作(这个原则也适用于其他集合类型:NSDictionary\NSSet等)。

#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:@""];
// 添加元素
[array addObject:@""];
[array addObject:@""]; // [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 = ;
// stu2:1
Student *stu2 = [[Student alloc] init];
stu2.age = ; // 对被添加的元素做一次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:@"", @"", @"", nil]; [array replaceObjectAtIndex: withObject:@""]; NSLog(@"%@", array);
} void arraySort() {
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"", @"", @"", nil]; [array sortUsingSelector:@selector(compare:)]; NSLog(@"%@", array);
}
上一篇:mybatis generator.xml 配置 自动生成model,dao,mapping


下一篇:SVD分解 解齐次线性方程组