参考:
http://stackoverflow.com/questions/990817/are-ints-always-initialized-to-0
1) Objective-C中,类的非静态 变量(class instance variable 或 ivar)默认都是初始化成0,由编译器保证,无需程序员自己手工初始化成0。
Object Allocation 中提到:
An allocation message does other important things besides allocating memory:
- retain count to one.
-
It initializes the object’s
isa
instance variable to point to the object’s class, a runtime object in its own right that is compiled from the class definition. -
It initializes all other instance variables to zero (or to the equivalent type for zero, such as
nil
,NULL
, and0.0
).
Programming With Objective-C 中提到:
The alloc
method has one other important task, which is to clear out the memory allocated for the object’s properties by setting them to zero. This avoids the usual problem of memory containing garbage from whatever was stored before, but is not enough to initialize an object completely.
2) 对全局变量上述规则也同样适用,即全局变量也会默认初始化成0:
// At global scope
int a_global_var; // guaranteed to be 0
NSString *a_global_string; // guaranteed to be nil
【一些特例】
- 局部变量(local variable)不会默认初始化成0 【yasi】在 XCode 6.1. 中试验的结果貌似不是这样的,即,local variable 也会默认初始化成0,建议对于 local variable 显式手工初始化成 nil
- 由 malloc() 或 realloc() 分配的变量不会默认初始化成0。注意:calloc() 分配的变量会显示初始化为0
【一些建议】
1) 根据 Transitioning to to ARC Release Notes,当 ARC 启用时,stack variables 会隐式地初始化成 nil。
然而,建议对 stack variables 保持手工初始化 nil 的习惯。Stack Variables Are Initialized with
nil
Using ARC, strong, weak, and autoreleasing stack variables are now implicitly initialized with
nil
2) 不要忘记,C++ 对象,以及在 Objc 中混用的 C++对象,仍然保持 C++ 的对象成员初始化规则,即 C++ 类成员变量不会默认初始化成0
Stack Variables Are Initialized with
nil
Using ARC, strong, weak, and autoreleasing stack variables are now implicitly initialized with
nil