Search code examples
iphoneobjective-cinitializationinstance-variablesself

Assigning ivars using self keyword in an object's init method


I've read that it's bad to use self.ivar = (convenience method) in and object's 'init' method, as this messes with inheritance.

However, if you know you're not going to subclass your object, is it ok to use the self keyword assignment?

i.e. self.iVar = [Object objectConvenienceMethod];

The reason I ask is this. I create a new object with its own init method, and in that method, I perform various initial assignments. Since I don't use the self keyword, I assign them directly to the iVars, and therefore use the alloc methods rather than the convenience methods. I.e.

iVar = [[Object alloc] init];

Or if I use a convenience method, I retain it. I.e.

iVar = [[Object convenienceMethod]retain]

But... when I run my program with the memory leak tool on, all of these assignments are identified as memory leaks.

If I can use the self keyword plus a convenience method instead of alloc-init, then this would avoid the problem.

If I choose to use the alloc-init approach though, where am I supposed to release the iVars?? Just in dealloc?

Thanks for your help :)

Michael


Solution

  • I am thinking your "enclosing" class is not being released, and hence its dealloc method is not being called resulting in your iVars not being released.