1
votes

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

3

3 Answers

2
votes

No, because it isn't only subclass behavior you need to take into account — superclass implementations and even the behavior of code generated by the framework (e.g. synthesized accessors and the black magic used to implement KVO) can also cause trouble. It will probably be OK, but that's still a significant chance of being not-OK. All in all, it's best just to follow Apple's recommendation and assign directly.

Assigning to ivars in init shouldn't be reported as leaks in a properly functioning program. If you're seeing that, there's some other problem that you need to address. Try reducing the problem to a minimal case that we can try out and ask about that — then we can tell what's wrong.

1
votes

If you alloc or retain them in your class's init method, you should release them in the corresponding dealloc method.

0
votes

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.