Ambiguous scenario for iPhone memory management
I have some difficulties to understand this scenario.
- I create an object
- I set its retained property to something
- I forget to release its property
- I release the object
As I didn't release the property in the dealloc method, will the scenario result in a memory leak or will the property be released automatically?
The way Cocoa works is that memory management always looks locally balanced, within any one method*. This is kind of the point. You should be able to tell whether you have a leak or error in a method just by looking at that one method. No global program knowledge required.
It is your responsibility to release an object if you received the object from a -copy, -alloc, -retain, or -new method.
If you do this:
[obj setProp:foo];
is it your responsibility to release foo? No - see rules. If obj retains it (and you're saying you happen to know that it does), then it is the responsibility of obj to release it, in its dealloc method if not sooner.
So if you did this, it's balanced, no matter what kind of property -prop
is.
id obj = [[MyObject alloc] init];
[obj setProp:foo];
[obj release];
*except for within the implementations of init, copy, dealloc, and accessor methods.
Yes, it's leak.
Retain, alloc will increase the counter by one. Release will decrease the counter. It will free the memory when the counter reaches zero.
Think of setter as this:
[newvalue retain];
[property release];
property = newvalue;
So..
- create an object => 0+1=1
- assign it to some object as a retain property => 1+1=2
- release the object => 2-1=1
You will have to release that object again sometime.
And, trust me autorelease
doesn't work quite well in the iphone environment.
精彩评论