Search code examples
objective-cinitializationinstance-variablesprimitive

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


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;
}

Solution

  • 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 to 0.