有一个未保存的id对象的列表? [英] Having a list of unretained id objects?

查看:139
本文介绍了有一个未保存的id对象的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实现一个引用了一堆未保留的 id 对象的类/对象?

How can I implement a class/object that has a reference to a bunch of non-retained id objects?

我想要的东西类似于 UIControl / NSControl has: addTarget: )target action:(SEL)action ...; (在我的例子中,我不需要 UIControlEvents 部分)。我想使用这个目标/行为模式(并且最好远离委托模式),但是我需要确保添加到我的对象的目标不会被保留或保留周期可能发生。

I want something similar to what UIControl/NSControl has: addTarget:(id)target action:(SEL)action ...; (in my case, though, I don't need the UIControlEvents part). I want to use this target/action pattern (and preferably stay away from the delegate pattern) but for that I need to make sure the targets added to my object are not retained or retain cycles might happen.

我想使用 malloc / 自由实现自己的数组,将是一个解决方案,但所有这些麻烦的气味,就像已经有一个解决方案在某处实现。是否有?

I think implementing my own array using malloc/free to make sure targets are not retained would be one solution, but all this hassle smells like there is already a solution implemented somewhere. Is there?

推荐答案

在OS X上,您可以创建一个 NSPointerArray 将保留对其对象的弱引用 + [NSPointerArray weakObjectsPointerArray] ,或者(如果你想要一个字典) =http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSMapTable_class/Reference/NSMapTable.html =nofollow> NSMapTable ,它允许键和值之一或两者保持弱。

On OS X you can create an NSPointerArray that will keep weak references to its objects with +[NSPointerArray weakObjectsPointerArray], or (if you want a dictionary) an NSMapTable which allows either or both of the keys and values to be held weakly.

这些都不是目前在iOS上可用,但Core Foundation是。在OS X或iOS上,您可以使用 CFArray CFDictionary ,传递 NULL 为回调使集合不对其包含的对象进行内存管理。警告,如果你尝试使用这些,因为他们是他们的免费桥接Cocoa同行,该集合将不会兑现你的非保留/非复制的愿望。

Neither of those are available currently on iOS, but Core Foundation is. On either OS X or iOS you can use CFArray or CFDictionary, passing NULL for the callbacks to make the collection do no memory management of its contained objects. Be warned that if you try to use these as if they were their toll-free bridged Cocoa counterparts, the collection will not honor your non-retaining/non-copying desire. You'll have to use the CF functions to interact with them (or whip up a wrapper class).

您还可以在中包装您的对象。您也可以使用CF函数与它们交互(或者打包一个包装类) NSValue s,使用 valueWithNonretainedObject: ,并将它们放入Cocoa集合中( NSDictionary / NSarray )。该集合将拥有该值,但该值不会拥有其对象。

You can also wrap your objects in NSValues, using valueWithNonretainedObject:, and put those into a Cocoa collection (NSDictionary/NSarray). The collection will own the value, but the value will not own its object.

这篇关于有一个未保存的id对象的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆