为什么一个对象在销毁时是否为 Nil 很重要?
Why Does it Matter if An Object is Nil When Destroyed?
我正在阅读一本最新的书,运行 正在阅读 ARC 部分。它解释了这两个 ARC 限定符:
Weak: Weak indicates that the object should not be retained (does not increase retain count). The compiler will set to nil before
destruction.
__unsafe__unretained: Same as weak, but the object is not set to nil before it is destroyed.
我的问题是,对象在销毁之前是否设置为 nil 有什么关系?如果自动释放池摆动并释放了被销毁的对象,则它不再在内存中使用。那么,如果对象在被销毁之前设置为 nil 有什么关系呢?我唯一会想到的情况是如果它是一个单身人士...
From this SO answer:
__unsafe_unretained will continue pointing to the memory where an object was, even after it was deallocated. This can lead to crashes due to accessing that deallocated object.
您总是会使用 weak,因为它比 __unsafe_unretained(因此得名)安全得多。 Also from the same thread:
__unsafe_unretained can be useful for defining C arrays of NSString constants and the like, e.g. NSString __unsafe_unretained *myStrings = { @"Foo", @"Bar", @"Baz", nil };
你问:
My question is, why would it matter is the object is set to nil or not before it's destroyed?
不是 "object" 被设置为 nil
,而是引用该对象的 weak
变量。假设您有两个对某个对象的引用,一个 strong
和一个 weak
。假设您删除了 strong
引用(例如,将该变量设置为 nil
)。现在该对象没有更多的强引用,因此将被释放。 weak
引用的美妙之处在于,既然对象已被释放,弱引用也将设置为 nil
,确保您不会不小心尝试使用该内存,即使它已经很长时间了因为已被释放并可能被重新用于其他目的。
这与 assign
或 unsafe_unretained
行为形成对比:对象被释放后,如果您有其他 assign
引用它,该引用将保持不变,指向已释放的内存(这称为 "dangling pointer",指向不再存在的内容)。
我正在阅读一本最新的书,运行 正在阅读 ARC 部分。它解释了这两个 ARC 限定符:
Weak: Weak indicates that the object should not be retained (does not increase retain count). The compiler will set to nil before destruction.
__unsafe__unretained: Same as weak, but the object is not set to nil before it is destroyed.
我的问题是,对象在销毁之前是否设置为 nil 有什么关系?如果自动释放池摆动并释放了被销毁的对象,则它不再在内存中使用。那么,如果对象在被销毁之前设置为 nil 有什么关系呢?我唯一会想到的情况是如果它是一个单身人士...
From this SO answer:
__unsafe_unretained will continue pointing to the memory where an object was, even after it was deallocated. This can lead to crashes due to accessing that deallocated object.
您总是会使用 weak,因为它比 __unsafe_unretained(因此得名)安全得多。 Also from the same thread:
__unsafe_unretained can be useful for defining C arrays of NSString constants and the like, e.g. NSString __unsafe_unretained *myStrings = { @"Foo", @"Bar", @"Baz", nil };
你问:
My question is, why would it matter is the object is set to nil or not before it's destroyed?
不是 "object" 被设置为 nil
,而是引用该对象的 weak
变量。假设您有两个对某个对象的引用,一个 strong
和一个 weak
。假设您删除了 strong
引用(例如,将该变量设置为 nil
)。现在该对象没有更多的强引用,因此将被释放。 weak
引用的美妙之处在于,既然对象已被释放,弱引用也将设置为 nil
,确保您不会不小心尝试使用该内存,即使它已经很长时间了因为已被释放并可能被重新用于其他目的。
这与 assign
或 unsafe_unretained
行为形成对比:对象被释放后,如果您有其他 assign
引用它,该引用将保持不变,指向已释放的内存(这称为 "dangling pointer",指向不再存在的内容)。