Assume following code,
NSString *str=[[NSString alloc] initWithString:@"sagar"];
[str autorelease];
I have seen many times that, Most of the programmers do prefer to put alloc, init simultaneously within one statement.
Here, I am asking for the possibility of dividing autorelease for next statement.
- For example, It is recommended to put init with alloc statement.
Is it same for autorelease ?
That’s because the instance returned by the initialiser is not necessarily the one returned by
+alloc. For example, this is wrong and will crash your program:because in this case
-initWithString:causes the deallocation of the previous instance, andstrends up pointing to a deallocated object. This can be fixed by:so that
strpoints to the different instance returned by-initWithString:. The form:guarantees that
strpoints to the correct instance.That said,
-autoreleaseis different. Unless it’s been overridden by an evil djinn, it always returns the receiver itself. This means that both:and:
are correct and work in the same manner.
As for the distinction between:
and:
some people prefer to use
-autoreleasein tandem with allocation to avoid forgetting to autorelease the instance later. Others prefer to place it in thereturnstatement (if any):to make (more) explicit that the method/function returns an autoreleased object.