[Objective-C] 哪些变量默认初始化为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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值