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
基础教程推荐
- iOS4 创建后台定时器 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
