Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which increases the retain count: alloc or init?

When we need create an object and take ownership of it we write

NSObject *someObject = [[NSObject alloc] init];

After that someObject's retain count will be equal to 1. Which method increases the count, alloc or init, and where in Apple's docs is this behavior described?

like image 397
Rostyslav Druzhchenko Avatar asked Nov 27 '22 14:11

Rostyslav Druzhchenko


1 Answers

After that someObject's retainCounter will be equal 1. Question is which method increases retainCounter alloc or init and there in Apple docs this behavior is described?

"Neither", "Both", or "One or the Other" would all be correct answers. A better answer would be "it is an implementation detail and you need to focus on the general, non implementation dependent rule".

First, ditch the notion of absolute retain counts. It is a useless way to think of this.

+alloc returns an object with a +1 retain count. Whatever is returned by +alloc must be -released somewhere. Wether or not the actual retain count is 1 or not is entirely an implementation detail and it often is not 1 for many of Apple's classes.

-init consumes the retain count of the messaged object and produces an object of retain count +1 (not 1, but "plus 1"); the result returned from init must be released to be managed correctly.

More often than not, init simply calls return self; without internally manipulating the retain count. This preserves the above rule.

Sometimes it doesn't, though, which is why you always have to have self = [super init] (checking the return value, of course) in your initializers and why you should never do something like Foo *f = [Foo alloc]; [f init];.

like image 156
bbum Avatar answered Dec 21 '22 12:12

bbum