Local variables set to nil? (Objective-C)

拜拜、爱过 提交于 2019-11-27 12:08:51

With ARC enabled, your Objective-C object pointer variables will be set to nil regardless of where you create them.

Without ARC, and for built in C types, your variables will not be initialized.

Instance variables of Objective-C objects are always set to 0 (or nil) when you allocate an object.

Statics are set to 0.

I've gotten in the habit of always giving a default value to variables, though. It's been a good habit to have.

No2. Just as in "plain" C, local variables are not assigned a default value. (Although you may get lucky the first time part of the stack is used: do not rely on this!.)

Anyway, nil is 01 -- that is, nil == 0 is always true -- so NSLog("@%i", nil) says "hey, log the argument as an integer", which is ... 0.

Happy coding.


1 See nil in gdb is not defined as 0x0? which covers the technical definition, including the Objective-C++ case, in more detail. Note that the type changes depending upon architecture as well so "@%i" could very well be wrong for a particular system.

2 See wbyoung's answer for ARC-specific rules.

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