NSArray of weak references (__unsafe_unretained) to objects under ARC(对 ARC 下对象的弱引用 (__unsafe_unretained) 的 NSArray)
问题描述
我需要在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对 ARC 下对象的弱引用 (__unsafe_unretained) 的 NSArr
基础教程推荐
- - (CGRect)convertRect:(CGRect)rect toView:(UIView *)view 如何工作 2022-01-01
- 突出显示朗读文本(在 iPhone 的故事书类型应用程序中) 2022-01-01
- 在 appComponent dagger 2 中动态添加测试模块? 2022-01-01
- 新的@SystemApi 注解是什么意思,和@hide 有什么区别 2022-01-01
- 我的 UIImageView 的任务 2022-01-01
- 在 iOS8 中无法获得正确的键盘高度值 2022-01-01
- 在 Android 模拟器中激活网络位置提供程序? 2022-01-01
- 如何将多个组件添加到 PickerView? 2022-01-01
- Android:STATE_SELECTED不工作 2022-01-01
- 可可/目标C(OSX不是iOS)从子对象访问父对象 2022-01-01
