1. 程式人生 > >[Objective-C] 哪些變數預設初始化為0

[Objective-C] 哪些變數預設初始化為0

參考:

1) Objective-C中,類的非靜態 變數(class instance variable 或 ivar)預設都是初始化成0,由編譯器保證,無需程式設計師自己手工初始化成0

An allocation message does other important things besides allocating memory:

  • It sets the object’s 

    retain count to one.
  • It initializes the object’s isainstance 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 nilNULL, and 0.0).

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

【一些建議】

Stack Variables Are Initialized with nil

Using ARC, strong, weak, and autoreleasing stack variables are now implicitly initialized with nil

然而,建議對 stack variables 保持手工初始化 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