blaackjack
blaackjack

Reputation: 1

Xcode compiler doesn't set my variable (and pointer) initial value to 0 or nil

this is very annoying, since now my values are stored as if they contain something by default (like in C). All my OO stuff are now broken since my delegate are always something. I was wonderin why Xcode do this to me, since by default Xcode always set the variable value to 0 or nil.

So if I do NSArray* anArray; and then NSLog(%@"%@", anArray);

It could crash or log hasard last allocated memory. This is very frustrating.

Upvotes: 0

Views: 1080

Answers (2)

Paul R
Paul R

Reputation: 212979

Objective C behaves much the same as C in this regard, i.e. non-global variables are not initialised by default. Code defensively and always initialise pointer variables explicitly (either to NULL or to a valid address).

Upvotes: 1

Eric Towers
Eric Towers

Reputation: 4215

C, Objective C, and C++ all initialize global variables to zero/null/Nil. Local variables are not automatically initialized and must be explicitly initialized.

Additionally, a pointer to a NSArray is not an NSArray. Before using that pointer, you should arrange for an NSArray to actually be at the end of it. For instance, make a new one, something more like

    // NSArray* anArray = new NSArray;  // if using a C++ backend
    NSArray* anArray = [[NSArray alloc] init];  // if using an Objective-C backend
    // ...
    NSLog(%@"%@", anArray);

Upvotes: 2

Related Questions