问题描述
比方说,我在写我自己的函数,它在CFDataRef对象,做了它,并返回另一个CFDataRef对象:
Let's say I'm writing my own function that takes in a CFDataRef object, does something to it, and returns another CFDataRef object:
CFDataRef transformData(CFDataRef inData)
{
//Question 1: Should I call CFRetain(data) here to make sure it doesn't
//go away? (This of course would involve releasing data just before returning
//from this function, or as soon as I no longer need data.)
CFDataRef outData;
//Somehow produce the new outData from inData (and assume we are the
//owner of outData, since we created it right here).
//Question 2: What, if anything, should I do with outData before
//returning it? I'm unsure of this, because CF doesn't have any
//autoreleasing mechanism.
return outData;
}
正如你所看到的,我有两个问题,他们都在上面的code包含的权利。
As you can see, I have two questions and they are contained right in the code above.
推荐答案
有关问题1:在顶部把它保留下来,然后松开以后会是线程安全的,在案件的唯一原因,你在哪里得到从一个线程调用而另一个线程释放数据的最后归属,但不会帮助:即使你保留的对象,释放可能发生有人叫你在此之前,甚至之前,在这种情况下,问题仍然发生,你'只有已经使它罕见。所以我说不用担心。
For question 1: The only reason to retain it at the top and release it later would be thread-safety, in the case where you get called from one thread and another thread releases the last ownership of the data, but that won't help: Even if you retain the object, the release might happen before then, or even before you're called, in which case the problem still happens and you've only made it rarer. So I say don't worry about it.
有关问题2:重命名功能 CreateDataByTransformingData code>。然后,根据CF存储管理规则中,你的函数返回调用者必须释放所有权。
For question 2: Rename your function to CreateDataByTransformingData
. Then, according to CF memory-management rules, your function returns an ownership which the caller must release.
备用解决问题2:演员到的NSData *
并发送一个自动释放
消息。 (这需要您使用MRC,没有ARC,至少在这个模块/类。)
Alternate solution to question 2: Cast to NSData *
and send it an autorelease
message. (This requires that you use MRC, not ARC, at least for this module/class.)
[增加了2013年11月1日]备选替代的解决方案:需要OS X 10.9或更高版本,并使用新的 CFAutorelease
功能。
[Added 2013-11-01] Alternate alternate solution: Require OS X 10.9 or later and use the new CFAutorelease
function.
这篇关于保留和"自动释放"在核心基础的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!