[OC Foundation框架 - 9] NSMutableArray

可变的NSArray,可以随意添加OC对象

 
1.创建
 1 void arrayCreate()
 2 {
 3     NSMutableArray *array = [NSMutableArray arrayWithObject:@"1"];
 4    
 5     [array addObject:@"2"];
 6     [array addObject:@"3"];
 7    
 8     [array removeObject:@"2"];
 9     NSLog(@"%@", array);
10 }
 
NSMutableArray 不能使用@[]创建
 
 
2.内存管理
当Array release的时候,里面的元素也会release一次
 1 void memoryManage()
 2 {
 3     NSMutableArray *array = [NSMutableArray array];
 4     Student *stu1 = [Student initWithAge:12];
 5     Student *stu2 = [Student initWithAge:42];
 6    
 7     //Will retain stu1 one time automatically
 8     [array addObject:stu1];
 9     [array addObject:stu2];
10    
11     NSLog(@"add--> stu1: %zi", [stu1 retainCount]);
12    
13     //Will release stu1 one time automatically
14     [array removeObject:stu1];
15     NSLog(@"remoe--> stu1: %zi", [stu1 retainCount]);
16    
17     NSLog(@"%@", array);
18    
19     //All element will be released one time
20     [array release];
21 }
 
3.替换元素
1 void replaceArray()
2 {
3     NSMutableArray  *array = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil];
4     [array replaceObjectAtIndex:2 withObject:@"a"];
5     NSLog(@"%@", array);
6 }
 
4.排序
1 void arraySort()
2 {
3     NSMutableArray *array = [NSMutableArray arrayWithObjects:@"1", @"3", @"3", nil];
4     [array sortedArrayUsingSelector:@selector(compare:)];
5     NSLog(@"%@", array);
6 }
 
5.删除元素
1         NSMutableArray *a = [NSMutableArray array];
2         [a addObject:@1];
3         [a addObject:@2];
4         [a removeObject:@1];
5         NSLog(@"%@", a);
6         [a removeAllObjects];
7         NSLog(@"%@", a);
 
 
posted @ 2014-11-24 19:10  HelloVoidWorld  阅读(180)  评论(0编辑  收藏  举报