我需要在 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模板网!