NSArray对ARC下的对象的弱引用(__unsafe_unretained) [英] NSArray of weak references (__unsafe_unretained) to objects under ARC
问题描述
我需要在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
而不是 __弱
。
编辑(2015-02-18):
EDIT (2015-02-18):
对于那些想要使用真正的 __弱的人
指针(不是 __ 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.
这篇关于NSArray对ARC下的对象的弱引用(__unsafe_unretained)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!