views:

32

answers:

2

Hey guys,

i have some difficulties to understand this scénario ...

  • 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 scénario result in a memory leak or Will the property be released automatically ?

And yes, i read the memory management guide ;)

cheers,

gotye.

A: 

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.

Bird
This is incorrect, and autorelease does indeed work on the iPhone.
Ken
It's ok for a small number of autorelease objects. But, I still suggest that you should avoid using it.You can release the property in dealloc funcsince `[nil release]` doesn't cause you any trouble at all.
Bird
A: 

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.

Ken