On page 326 in the book Programming in Objective-C 2.0 the author says:
myNumber = [[NSNumber alloc] initWithInt: 1000];
Of course, based on previous discussions, if you create myNumber
this way, you are re- sponsible for subsequently releasing it when you’re done using it with a statement such as follows:
[myNumber release];
My question is:
Does this mean that if I create an NSNumber
object with this statement
NSNumber *myNumber = [NSNumber numberWithInteger: 100];
I don't have to release the object myNumber
myself?
This link is your bible
In the case of [NSNumber numberWithInt:]
it returns an autoreleased object, and you don't need to do anything to release it properly. Unless you retain
it, of course, in which case you would call release
on it, likely from your dealloc
method.
[[NSNumber alloc] initWithInt:]
returns an object with a retain count of one (from calling alloc
). You are responsible for releasing any object created this way.
Simple rules for memory management:
- When you make an object with alloc, you have the responsibility to release/autorelease it.
- When you retain an object, you have the responsibility to release/autorelease it.
- The others, it's not your responsibility, if you release/autorelease object which you don't own, crash.
If you call alloc
, retain
, new
, copy
(or mutableCopy
), you are responsible for releasing the object.
In all other cases the object is autoreleased, and must NOT call release.
There are no compiler or run time rules that enforce this*, it's just a language naming convention, but it's used everywhere, so you can count on it to be true.
Your own code should follow this convention as well.
*Automatic Reference Counting relies on the naming convention to function properly. See http://clang.llvm.org/docs/AutomaticReferenceCounting.html#objects.operands.retained_returns for details.