views:

42

answers:

2

Hi, sthis is very annoying, since now my values are stored as if they contain somethin by default (like in c). All my OO stuff are now broken since my delegate are always somethin. 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

+1  A: 

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).

Paul R
A: 

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);
Eric Towers
Thks for the reply. Okay for the pointer stuff. The fact is i'm so angry i said stupidity. In my last project my local primitives variable were set to 0. Here even my BOOL variable are not false by default. And i know GCC compiler do the dirty job for me. But now i don't understand why this is not the expected behavior.
blaackjack
@blaackjack: it sounds like you've been relying on the fact that your stack just happens to contain a lot of 0s - your previous project may well crash in obscure and interesting ways at some time in the future as a result of this very dangerous coding practice. Get into the habit of initialising local variables explicitly (and go back and fix your old project !).
Paul R
yeah, for sure this is the lesson of the day. For me this is like i thought 2+2 = 5 and now you learn me 2+2 = 4. As Eric said, sure i have mistaken the global and local behavior. This is when making big mistakes like this one that we learn ^^
blaackjack