如果函数遵循“获取规则”(如 Apple 此处所述:https://developer.apple.com/library/ios/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html#//apple_ref/doc/uid/20001148-SW1)
在您有机会调用 CFRetain 之前,是否可以释放结果(因为其他地方的 CFRelease)?
以下面的代码为例:
// Using CFAttributedStringGetString as an example
// but I am asking about *any* GET rule function
CFStringRef * str = CFAttributedStringGetString(...);
CFRetain(str);
当我们实际调用 CFRetain 时,我们是否可能持有对释放的 CFString 的引用?如果不是,为什么不呢?如果可能的话,我该如何避免这种情况的发生?
最佳答案
对于这段代码:
CFStringRef * str = CFAttributedStringGetString(...);
CFRetain(str);
不可能持有对 CFString
对象的悬空引用。
这是因为:
- 每个线程都有自己的堆栈,
str
位于该堆栈上,因此对线程私有(private),因此没有其他线程引用字符串对象。 - 自动释放池不能被清空,因为它只发生在 runloop 的迭代之间,并且由于您还没有从该方法返回,您还没有完成 runloop 的迭代。
关于objective-c - 调用 'Get Rule' 函数和保留结果之间是否存在竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35500064/