問題描述
我需要在 NSArray 中存儲對對象的弱引用,以防止保留循環.我不確定要使用的正確語法.這是正確的方法嗎?
I need to store weak references to objects in an NSArray, in order to prevent retain cycles. I'm not sure of the proper syntax to use. Is this the correct way?
Foo* foo1 = [[Foo alloc] init];
Foo* foo2 = [[Foo alloc] init];
__unsafe_unretained Foo* weakFoo1 = foo1;
__unsafe_unretained Foo* weakFoo2 = foo2;
NSArray* someArray = [NSArray arrayWithObjects:weakFoo1, weakFoo2, nil];
請注意,我需要支持 iOS 4.x,因此使用 __unsafe_unretained
而不是 __weak
.
Note that I need to support iOS 4.x, thus the __unsafe_unretained
instead of __weak
.
編輯(2015-02-18):
EDIT (2015-02-18):
對于那些想要使用真正的 __weak
指針(而不是 __unsafe_unretained
)的人,請查看以下問題:ARC下歸零弱引用的集合
For those wanting to use true __weak
pointers (not __unsafe_unretained
), please check out this question instead: Collections of zeroing weak references under ARC
推薦答案
正如 Jason 所說,你不能讓 NSArray
存儲弱引用.實現 Emile 的建議的最簡單的方法是:將一個對象包裝在另一個存儲弱引用的對象中:
As Jason said, you can't make NSArray
store weak references. The easiest way to implement Emile's suggestion of wrapping an object inside another object that stores a weak reference to it is the following:
NSValue *value = [NSValue valueWithNonretainedObject:myObj];
[array addObject:value];
另一個選項:一個 類別,它使 NSMutableArray
可選擇地存儲弱引用.
Another option: a category that makes NSMutableArray
optionally store weak references.
請注意,這些是不安全的未保留"引用,而不是自歸零弱引用.如果在對象被釋放后數組仍然存在,你就會有一堆垃圾指針.
Note that these are "unsafe unretained" references, not self-zeroing weak references. If the array is still around after the objects are deallocated, you'll have a bunch of junk pointers.
這篇關于對 ARC 下對象的弱引用 (__unsafe_unretained) 的 NSArray的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!