关闭

[Objective-C] 哪些变量默认初始化为0

1507人阅读 评论(0) 收藏 举报

参考:

http://stackoverflow.com/questions/1786781/are-instance-variables-set-to-nil-by-default-in-objective-c

https://developer.apple.com/library/mac/documentation/General/Conceptual/CocoaEncyclopedia/ObjectAllocation/ObjectAllocation.html#//apple_ref/doc/uid/TP40010810-CH7-SW1

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:

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

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


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2718834次
    • 积分:23648
    • 等级:
    • 排名:第274名
    • 原创:158篇
    • 转载:596篇
    • 译文:0篇
    • 评论:202条
    最新评论