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?
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 -release
d 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 release
d 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];
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With