Are primitive instance variables initialized by default in Objective-C?

In the following code, is it safe to use _test and expect it to be NO ? Or do I need to always explicitly initialize it to - (id)init ?

 @implementation Test { BOOL _test; } 
+7
source share
2 answers

It is safe to assume that all instance variables will be initialized to 0.

However, this does not apply to locally / method scope variables, which, if not initialized manually, indicate unwanted messages.

In the future, as Rob Napier notes, this can be found in the documentation for + (id)alloc :

The isa instance variable of the new instance is initialized with a data structure that describes the class; The memory for all other instance variables is set to 0 .

+9
source

I use it for initialization explicitly, mainly because of traceability and readability. But when you look at the definition of BOOL , you will see that NO is nothing more than #define for 0. Because of this, I assume that you can confidently expect _test be NO .

really nice post about Boolean and their handling of Objective-C: BOOL vs bool

0
source

All Articles