gpt4 book ai didi

cocoa - 如何在垃圾收集环境中确定性地释放 Core Foundation 对象?

转载 作者:行者123 更新时间:2023-12-03 17:00:26 26 4
gpt4 key购买 nike

我在垃圾收集环境中使用 Core Foundation 方法。根据documentation调用 CFRelease 只是减少引用计数,但不会释放对象:

The difference between the garbage-collected environment and reference-counted environment is in the timing of the object’s deallocation. In a reference counted environment, when the object’s retain count drops to 0 it is deallocated immediately; in a garbage-collected environment, what happens when a Core Foundation object's retain count transitions from 1 to 0 depends on where it resides in memory:

  • If the object is in the malloc zone, it is deallocated immediately.
  • If the object is in the garbage collected zone, the last CFRelease() does not immediately free the object, it simply makes it eligible to be reclaimed by the collector when it is discovered to be unreachable—that is, once all strong references to it are gone. Thus as long as the object is still referenced from an object-type instance variable (that hasn't been marked as__weak), a register, the stack, or a global variable, it will not be collected.

有时我会打开持有成本昂贵的资源,例如网络上的文件:

CGImageSourceRef imageSource = CGImageSourceCreateWithURL(url, NULL);

是否可以确定地释放 imageSource 对象(关闭、处置、销毁、杀死 SCSS ),而无需等待垃圾收集器?

.Net Framework 有 IDisposable 接口(interface),我可以这样做:

using (Font myFont = new Font("Arial", 10.0f))
{
// use myFont
} // compiler will call Dispose on myFont

Objective-C/Cocoa 中有类似的东西吗?

最佳答案

请参阅 Apple 文档 using CoreFoundation with garbage collection 。 TLDR 版本:分配 kCFAllocatorMallocZone 中的对象,将它们排除在垃圾收集系统之外。

关于cocoa - 如何在垃圾收集环境中确定性地释放 Core Foundation 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1949778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com