天天看點

[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);      

轉載于:https://www.cnblogs.com/hellovoidworld/p/4119408.html

繼續閱讀