用CTFontCreateWithGraphicsFont避免内

用CTFontCreateWithGraphicsFont避免内

本文介绍了如何使用CTFontCreateWithGraphicsFont避免内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've reduced a leak issue to this easy to compile code which shows after CTFontCreateWithGraphicsFont use and release ct_font, an extra ref to cg_font will be left. Is this an internal Apple ref count issue or am I missing something around like having to double release cg_font or changing order of the releases? Thanks.

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

编译并运行后的结果:

cg_font:1

cg_font: 1

推荐答案

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

The retain of the CGFont happens in the TInMemoryBaseFont constructor:

#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 析构函数(出于未知原因).

It's not matched with a release upon releasing the CTFont, probably because the TInMemoryBaseFont destructor is never called (for unknown reasons).

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

This isn't a solution, but might help someone coming along debug the problem further.

这篇关于如何使用CTFontCreateWithGraphicsFont避免内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 06:14