objective-c - 整数总是初始化为0吗?

在 Objective-C 中指望 ints 总是被初始化为 0 是否安全?

更具体地说,当新实例化具有 int ivars 的对象时,假设其 ivars 的值为 0 是否安全?

最佳答案

是的,类实例变量始终初始化为 0(或 nilNULLfalse,具体取决于确切的数据类型) .见 Objective-C 2.0 Programming Language :

The alloc method dynamically allocates memory for the new object’s instance variables and initializes them all to 0—all, that is, except the isa variable that connects the new instance to its class.


编辑 2013-05-08
苹果似乎已经删除了上述文件(现在链接到 The Wayback Machine)。 (当前)事件文档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.


但是,这对于类的实例变量是正确的;对于在全局范围内声明的 POD 类型也是如此:

// At global scope
int a_global_var;  // guaranteed to be 0
NSString *a_global_string;  // guaranteed to be nil

有一个异常(exception),对于局部变量,或者对于使用 malloc()realloc() 分配的数据,它为真; calloc() 也是如此,因为 calloc() 明确地将其分配的内存清零。

一个异常(exception)是,当启用自动引用计数 (ARC) 时,指向 Objective-C 对象的堆栈指针被隐式初始化为 nil;但是,将它们显式初始化为 nil 仍然是一种好习惯。来自 Transitioning to to ARC Release Notes :

Stack Variables Are Initialized with nil

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

在 C++(以及 Objective-C++ 中使用的 C++ 对象)中,类实例变量也零初始化。您必须在构造函数中显式初始化它们。

https://stackoverflow.com/questions/990817/

相关文章:

ios - 如何调用 iPhone map 以获取当前位置作为起始地址的方向

ios - 在主线程上调用方法?

ios - NSPredicate 用于测试 NULL 和空白字符串

iphone - iOS 7 UIRefreshControl tintColor 不适用于 beg

ios - 找不到符号 : kUTTypeImage

ios - 是否可以调试 "Terminated due to memory error"?

ios - 如何为 NSDate 添加一个月?

iphone - 实现 copyWithZone : 时的最佳实践

objective-c - 在 Objective-C 中从字符串中删除空格

objective-c - 删除 NSString 的最后一个字符