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

旧街凉风 提交于 2019-12-13 06:39:18

问题


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



来源:https://stackoverflow.com/questions/3989377/xcode-compiler-doesnt-set-my-variable-and-pointer-initial-value-to-0-or-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!