NSDictionary 中的弱对象?
我想在 NSDictionary 中存储对对象的清零弱引用。这是对父 NSDictionary
的引用,因此我可以爬取大型结构而无需搜索。
我不能在这里使用__weak
;即使我的本地引用很弱,NSDictionary
也会存储对弱引用对象的强引用。当然,NSDictionary
不能有 nil
对象。
我使用的是 iOS,而不是 Mac,因此 NSHashTable
不可用。我只希望一个对象是弱的;其余的应该还是很强的。
(我将发布我的答案,因此如果没有更好的答案,我会将某些内容标记为已接受。但我希望有人有更好的答案。)
I would like to store a zeroing weak reference to an object in a NSDictionary
. This is for a reference to a parent NSDictionary
, so I can crawl back up a large structure without searching.
I can not use __weak
here; even if my local reference is weak, the NSDictionary
will store a strong reference to the object that was weakly referenced. And, of course, NSDictionary
can't have nil
objects.
I'm on iOS, not Mac, so NSHashTable
isn't available. And I only want one object to be weak; the rest should still be strong.
(I'm going to post my answer, so I have something to mark as accepted if there's no better answer. But I'm hoping someone has a better answer.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 iOS 6+ 中,您可以使用 NSMapTable 并选择您希望对象和/或键变弱还是变强。
In iOS 6+ you can use NSMapTable and choose if you want objects and/or keys to be weak or strong.
我已经决定用单个成员定义一个“容器”类,如下所示:
并使用它:
我认为这对我有用,但似乎没有更好的内置方法来基础。
I've settled on defining a "container" class with a single member, like this:
And using it:
I think this will work for me, but it seems crazy that there's no better way built in to Foundation.
有一个内置的方法;只需使用:
然后稍后要访问该对象,请使用:
如果该值自添加以来已被释放,那么“object”在 iOS 4.x 下将是无效指针,并且(我假设)在 5 下将为 nil。 x 启用了 ARC。
编辑:我的假设是错误的 - 它在 ARC 下并不弱(参见下面的讨论)。
There is a built-in way; just use:
Then to access the object later, use:
If the value has been released since you added it then "object" will be an invalid pointer under iOS 4.x, and (I'm assuming) will be nil under 5.x with ARC enabled.
EDIT: my assumption was wrong - it's not weak under ARC (see discussion below).