In the following code, is it safe to use _test
and expect it to have a vaue of NO
? Or do I need to always explicitly initialize it in - (id)init
?
@implementation Test {
BOOL _test;
}
Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor. Instance variables can be accessed directly by calling the variable name inside the class.
A primitive-type variable can store exactly one value of its declared type at a time. Primitive-type instance variables are initialized by default. Variables of types byt e, char , short , int , long , float and double are initialized to 0 .
An instance variable is a variable that exists and holds its value for the life of the object. The memory used for instance variables is allocated when the object is first created (through alloc ), and freed when the object is deallocated.
It is safe to assume that all instance variables will be initialized to 0.
This however is not the case for locally/method scoped variables which, if not manually initialized, will point to junk.
For future reference, as Rob Napier points out, this can be found in the documentation for + (id)alloc
:
The
isa
instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to0
.
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