Yes, class instance variables are always initialized to 0 (either nil
, NULL
or false
, depending on the exact data type). See Objective-C 2.0 Programming Language :
The alloc
method dynamically allocates memory for new instances of object instances and initializes them all 0-all, that is, with the exception of the isa
variable, which binds the new instance to its class.
EDIT 2013-05-08
Apple seems to have deleted the above document (it is now associated with The Wayback Machine). In the currently active document, Objective-C Programming contains a similar link:
The alloc
method has another important task, which is to clear the memory allocated for the properties of objects by setting them to zero. This avoids the usual problem with memory containing garbage from what was previously saved, but not enough to completely initialize the object.
However, this is true only for class variables; this is also true for POD types declared globally:
// At global scope int a_global_var; // guaranteed to be 0 NSString *a_global_string; // guaranteed to be nil
With one exception, this does not apply to local variables or to data allocated using malloc()
or realloc()
; this is true for calloc()
since calloc()
explicitly discards the allocated memory.
The only exception is that when automatic reference counting (ARC) is enabled, stack pointers to Objective-C objects are implicitly initialized to nil
; however, it is still good practice to explicitly initialize them to nil
. From Going to ARC Release Notes :
Stack variables are initialized with nil
Using ARC, strong, weak, and auto-implementing stack variables are now implicitly initialized with nil
In C ++ (and the C ++ objects used in Objective-C ++), class instance variables are also not initialized to zero. You must explicitly initialize them in your constructors.