标签:
NSMutableArray 是一个可变数组,是NSArray的子类,但是不可以添加空值
创建NSMutableArray的方法
+(id)arrarWithCapacity:(NSInteger)numItems
-(id)initWithCapacity:(NSInteger)numItems
也可以用创建NSArray的方法创建NSMutableArray
当一个元素被加到集合中时,会执行一次retain操作;当一个元素从集合中移除时,会执行一次release操作,当集合被销毁时(dealloc),集合里面所有元素都执行一次release操作(这个原则同样适用于其它集合:NSDictionary\NSSet)
NSMutableArray *array=[NSMutableArray arrayWithObject:@“1”];
//Add elements
[array addObject:@”2”];
[array addObject:@”3”];
//removement
[array removeObject:@”2”];
[array removeLastObjects];
[array removeallobjects];
NSLog(@”%@”,array);
}
#pragma mark memory management
Student.h
@interface Student:NSObject
@property (nonatomic,assign) int age;
+(id)studentWithAge: (int) age;
@end
Student.m
@implemtation Student
+(id)studentWithAge: (int) age{
Student *stu= [[[Student alloc]init]autorelease];
stu.age=age;
return stu;
}
-(void)dealloc{
NSLog(@”age=%i is destroied”,_age);
[super dealloc];
}
@end
main.m
#import ”Student.h”
void arraymemory(){
NSMutableArray *arry=[NSMutableArray array];
Student *stu1=[Student studentWithAge:10];
Student *stu2=[Student studentWithAge:20];
[array addObject:stu1];
[array addObject:stu2];
NSLog(@”%zi”,[stu1 retainCount]);
//stu1,stu2 counter 2
[array removeObject:stu1];//stu1 counter1, stu2 counter 2
NSLog(@”%zi”,[stu1 retainCount]);
}
设置集合元素
-(void)setArray:(NSArry *)otherArray
添加一个元素
-(void)addobject:(id)anObject
添加otherArray的全部元素到集合中
-(void)addObjectsFromArray:(NSArray *)otherArray
插入一个对象,在Index地方插入一个对象
-(void)insertObjects:(id)anObject atIndex:(NSUInteger)index
在Indexs指定位置分别插入Objects中的元素
-(void)insertObjects;(NSArray *) objects atIndexs:(NSInsexSet *)indexs
#pragma mark replace elements
void arrayReplace(){
NSMutableArray *array=[NSMutableArray arrayWithObjects:@“1”,@”2”,@”3”,nil];
[array replaceObjectAtIndex:1 withObject:@”4”];//143
}
void arrayort(){
NSMutableArray *array=[NSMutableArray arrayWithObjects:@“1”,@”3”,@”2”,nil];
[array sortUsingSelector:(compare:)];//因为是可变数组所以没有返回值
NSLog(@”%@”,array);
}
标签:
原文地址:http://www.cnblogs.com/yesihoang/p/4547013.html