首页 > 代码库 > [OC Foundation框架 - 9] NSMutableArray
[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 automatically14 [array removeObject:stu1];15 NSLog(@"remoe--> stu1: %zi", [stu1 retainCount]);16 17 NSLog(@"%@", array);18 19 //All element will be released one time20 [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);
[OC Foundation框架 - 9] NSMutableArray
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。