对 ARC 下对象的弱引用 (__unsafe_unretained) 的 NSArray

NSArray of weak references (__unsafe_unretained) to objects under ARC(对 ARC 下对象的弱引用 (__unsafe_unretained) 的 NSArray)
本文介绍了对 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

AWS DynamoDB Batch Get Request - iOS(AWS DynamoDB 批量获取请求 - iOS)
DynamoDB auto incremented ID amp; server time (iOS SDK)(DynamoDB 自动递增 ID amp;服务器时间(iOS SDK))
dynamodb scanexpression with scan filter in objective-c(在objective-c中带有扫描过滤器的dynamodb scanexpression)
Getting full access to DynamoDB from my ios app using AWS Cognito Developer Identities(使用 AWS Cognito 开发人员身份从我的 ios 应用程序获得对 DynamoDB 的完全访问权限)
iOS framework with dependencies(具有依赖项的 iOS 框架)
Can#39;t change target membership visibility in Xcode 4.5(无法更改 Xcode 4.5 中的目标成员身份可见性)