iphone: which function/method call increases retainCounter? why mem management acting so strange?
hey people, I have a problem with my understanding of the memory management in the iphone.
I have the following strange situation:
CAGradientLayer * hButtonLayer = [[CAGradientLayer alloc] init];
NSLog(@"1: retaincounter is?: %d", [hButtonLayer retainCount]);
[hButtonLayer setBounds:tempButton.bounds];
NSLog(@"2: retaincounter is?: %d", [hButtonLayer retainCount]);
[hButtonLayer setColors:[NSArray arrayWithObjects:
[UIColor colorWithRed:0.2 green:0.3 blue:0.4 alpha:1.0],
[UIColor colorWithRed:0.4 green:0.5 blue:0.6 alpha:1.0], nil]];
NSLog(@"3: retaincounter is?: %d", [hButtonLayer retainCount]);
[[tempButton layer] insertSublayer:hButtonLayer atIndex:0];
NSLog(@"4: retaincounter is?: %d", [hButtonLayer retainCount]);
the output on the console shows the following:
1: retaincounter is?: 1
2: retaincounter is?: 2
3: retaincounter is?: 2
4: retaincounter is?: 3
ok, at 1) it's clear that the counter equals 1, because the Layer is alloced and initialized. but why is at 2) the "setBounds"-methid increasing the retain counter? and at 3) the retain counter is not increased by the "setColors"-method... and "insertSublayer" is again increasing the retain counter!
why are these methods increasing the counter? how should I know, if some framework-method increases something? I mean, if I decreas开发者_如何学运维es the retain counter and some framework-method didn't increase the counter, I will get a crash - how should I determine, if a method increases or not increases the retain counter?
thanks for any help!
Don't use the retain count as a debugging aid. Without knowing how system and third party frameworks are implemented you cannot know what the retain count should be.
It's very simple:
- If you
alloc
orcopy
orretain
an object, you "own" it and need to eitherrelease
orautorelease
it at some later point - Otherwise you do not own it and you are not responsible for its memory
As Stephen said, and any container like NSArray, NSDictionary will retain object. The sub views of UIView is maintained by array, so any added sub view will be retained.
The properties of an object, the memory management policy can be found on Apple's document. Or, you can go to the definition of the class and read its declaration.
精彩评论