7

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;
}
jscs
  • 63,694
  • 13
  • 151
  • 195
rid
  • 61,078
  • 31
  • 152
  • 193

2 Answers2

9

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.

Community
  • 1
  • 1
mmccomb
  • 13,516
  • 5
  • 39
  • 46
  • 3
    Just to provide the reference, read the docs for `+alloc`. Specifically, all ivars except `isa` are initialized to 0, but you shouldn't be messing with `isa` anyway. – Rob Napier May 18 '12 at 13:04
  • 1
    Note that auto object pointers _are_ in fact initialized to `nil` when compiled under ARC. – jscs May 18 '12 at 18:30
0

I'm used to initialize it explicitly, mainly because of traceability and readability. But when you look at the Definition of BOOL, you'll see that NO is nothing else than a #define for 0. Because of that, I assume you can safely expect _test to be NO.

a really good posting about Boolean and their handling is Objective-C : BOOL vs bool

Community
  • 1
  • 1
Herm
  • 2,956
  • 19
  • 32