Retaining and “autoreleasing” in Core Foundation

时间秒杀一切 提交于 2019-12-07 23:14:43

问题


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;
}

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.

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.

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.)

[Added 2013-11-01] Alternate alternate solution: Require OS X 10.9 or later and use the new CFAutorelease function.



来源:https://stackoverflow.com/questions/8627848/retaining-and-autoreleasing-in-core-foundation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!