XCode compiler doesn't set my variable (and po

2019-09-04 02:58发布

问题:

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:

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


回答2:

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