我已将泄漏问题简化为易于编译的代码,该代码在CTFontCreateWithGraphicsFont使用并释放ct_font后显示,将剩下对cg_font的额外引用。这是Apple内部引用计数的内部问题,还是我错过了某些东西,例如必须重新发布cg_font或更改发布顺序?谢谢。

#include <stdio.h>
#include <stdlib.h>
#include <ApplicationServices/ApplicationServices.h>

int main(int argc, char **argv) {
    FILE *f = fopen("/Library/Fonts/Tahoma.ttf", "rb");
    fseek(f, 0, SEEK_END);
    long fsize = ftell(f);
    fseek(f, 0, SEEK_SET);

    char* font = (char*)malloc(fsize);
    fread(font, fsize, 1, f);
    fclose(f);

    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, font, fsize, NULL);
    CGFontRef cg_font = CGFontCreateWithDataProvider(provider);
    CTFontRef ct_font = CTFontCreateWithGraphicsFont(cg_font, 36., NULL, NULL);
    CGDataProviderRelease(provider);

    //

    CFRelease(ct_font);
    CFRelease(cg_font);

    printf("ct_font: %d\ncg_font: %d\n", (int)CFGetRetainCount(ct_font), (int)CFGetRetainCount(cg_font));

    free(font);

    return 0;
}
编译运行后的结果:

最佳答案

CGFont的保留发生在TInMemoryBaseFont构造函数中:

#0  0x00007fff8928e4d0 in CFRetain ()
#1  0x00007fff86472906 in TInMemoryBaseFont::TInMemoryBaseFont(CGFont*) ()
#2  0x00007fff864728b8 in CTFontDescriptor::CTFontDescriptor(CGFont*, is_inmemory_t const&) ()
#3  0x00007fff8646cb30 in TDescriptorSource::CopyDescriptor(CGFont*, __CFDictionary const*) const ()
#4  0x00007fff8646c99a in TFont::InitDescriptor(CGFont*, __CTFontDescriptor const*) ()
#5  0x00007fff8646c7b4 in TFont::TFont(CGFont*, double, CGAffineTransform const*, __CTFontDescriptor const*) ()
#6  0x00007fff8646c775 in CTFontCreateWithGraphicsFont ()

它与释放CTFont时的发行版不匹配,可能是因为从未调用过TInMemoryBaseFont析构函数(出于未知原因)。

这不是解决方案,但可以帮助其他人进一步调试问题。

10-01 00:07