1.集合對(duì)象的內(nèi)存管理
- 當(dāng)一個(gè)對(duì)象加入到集合中,那么該對(duì)象的引用計(jì)數(shù)會(huì)+1
- 當(dāng)集合被銷毀的時(shí)候,集合會(huì)向集合中的元素發(fā)送release消息
NSMutableArray *arr = [[NSMutableArray alloc] init];
Person *p = [[Person alloc] init];
NSLog(@"retainCount = %lu", [p retainCount]);
[arr addObject:p];
NSLog(@"retainCount = %lu", [p retainCount]);
[p release];
NSLog(@"retainCount = %lu", [p retainCount]);
[arr release];
- 當(dāng)一個(gè)對(duì)象加入到集合中,那么該對(duì)象的引用計(jì)數(shù)會(huì)+1
- 當(dāng)把一個(gè)對(duì)象從集合中移除時(shí),會(huì)向移除的元素發(fā)送release消息
NSMutableArray *arr = [[NSMutableArray alloc] init];
Person *p = [[Person alloc] init];
NSLog(@"retainCount = %lu", [p retainCount]);
[arr addObject:p];
NSLog(@"retainCount = %lu", [p retainCount]);
[arr removeObject:p];
NSLog(@"retainCount = %lu", [p retainCount]);
[p release];
[arr release];
2.集合對(duì)象內(nèi)存管理總結(jié)
-
1.官方內(nèi)存管理原則
- 1> 當(dāng)調(diào)用alloc属愤、new、copy(mutableCopy)方法產(chǎn)生一個(gè)新對(duì)象的時(shí)候,就必須在最后調(diào)用一次release或者autorelease
- 2> 當(dāng)調(diào)用retain方法讓對(duì)象的計(jì)數(shù)器+1,就必須在最后調(diào)用一次release或者autorelease
-
2.集合的內(nèi)存管理細(xì)節(jié)
- 1> 當(dāng)把一個(gè)對(duì)象添加到集合中時(shí),這個(gè)對(duì)象會(huì)做了一次retain操作,計(jì)數(shù)器會(huì)+1
- 2> 當(dāng)一個(gè)集合被銷毀時(shí),會(huì)對(duì)集合里面的所有對(duì)象做一次release操作,計(jì)數(shù)器會(huì)-1
- 3> 當(dāng)一個(gè)對(duì)象從集合中移除時(shí),這個(gè)對(duì)象會(huì)一次release操作,計(jì)數(shù)器會(huì)-1
-
3.普遍規(guī)律
- 1> 如果方法名是add\insert開頭,那么被添加的對(duì)象,計(jì)數(shù)器會(huì)+1
- 2> 如果方法名是remove\delete開頭,那么被移除的對(duì)象,計(jì)數(shù)器-1