在C ++类中保留ARC对象

问题描述:

我有一些必须保留为c ++的代码,但是我需要将Objective-C对象存储在这些c ++类中.在将对象存储在此处时,将不会在其他任何地方引用这些对象,因此我不能将它们从我身下删除.在ARC之前,我只是保留了它们,然后才将它们放入c ++类,并在删除它们时自动释放它们.一切正常.

I have some code that must remain as c++, but I need to store objective-c objects in these c++ classes. The objects will not be referenced anywhere else while they are stored here, so I can't have them deleted out from under me. Before ARC, I just retained them before putting them into the c++ class, and autoreleased them when they were removed. Everything worked fines.

但是对于ARC,我不确定该怎么办.使c ++变量__unsafe_unretain足够吗?好像不是这样,因为一旦obj-c代码不再使用该对象,它将被删除,或者我不明白__unsafe_unretained的作用.我可以在ARC下调用CFRetain()和CFAutorelase()吗?

But with ARC, I'm not sure what to do. Is making the c++ variables __unsafe_unretained enough? Doesn't seem like it is because once the obj-c code isn't using that objects anymore it will be deleted, or am I not understanding what __unsafe_unretained does. Can I call CFRetain() and CFAutorelase() under ARC?

在ARC下处理此问题的正确方法是什么? NSArray到底在做什么以保持其存储的对象?

What is the right way to deal with this under ARC? What does NSArray do down deep to keep the objects it is storing?

您可以在ARC下调用CFRetain和CFRelease.您有责任用CFRelease平衡每个CFRetain,因为ARC对这些功能没有任何关注.

You can call CFRetain and CFRelease under ARC. You are responsible for balancing each CFRetain with a CFRelease, because ARC does not pay any attention to these functions.

没有CFAutorelease功能.您可以使用objc_msgSend(myObject, sel_registerName("autorelease"))执行自动释放.您在此处跳过的篮球应该是一个危险信号,表明您正在做某事,这可能是错误的.

There is no CFAutorelease function. You could perform an autorelease using objc_msgSend(myObject, sel_registerName("autorelease")). The hoops you are jumping through here should be a red flag that you're doing something that's probably wrong.

通常,最好在ARC下找到一种方法,以免将对象引用存储在其他未类型化的内存blob中.请注意,C ++对象的成员变量可以限定为__strong__weak (如果将它们编译为Objective-C ++).

Generally it's better under ARC to find a way not to store object references in otherwise-untyped blobs of memory. Note that member variables of C++ objects can be qualified __strong or __weak if you compile them as Objective-C++.

Mac OS X 10.9和iOS 7.0的公共SDK包含CFAutorelease功能,即使在ARC中也可以使用该功能.

The public SDKs of Mac OS X 10.9 and iOS 7.0 include a CFAutorelease function, which you can use even under ARC.