Search code examples
iosswiftmemory-managementcore-graphicscore-text

iOS Swift 5, Auto Release CoreText & CoreGraphics memory


I am using CoreText and CoreGraphics to load fonts from files within a directory, and then categories them according to the supported unicode characters in the font metadata using the following code, in a for loop :

if let provider = CGDataProvider(url: fontFileURL as CFURL) {
    if let font = CGFont(provider) {
        let ctFont = CTFontCreateWithGraphicsFont(font, 12, nil, nil)

        let chSet = CTFontCopyCharacterSet(ctFont)

        let cSet = chSet as CharacterSet

        let isAr = cSet.contains(Unicode.Scalar.init(unicodeScalarLiteral: "ب"))
        let isEn = cSet.contains(Unicode.Scalar.init(unicodeScalarLiteral: "b"))
        print(++index, isAr, isEn)
    }
}

but at some point in time before the fore loop finished looping the files, the app crashed with the error message Terminated due to memory issue, so I suspect that either one of these four function leaks memory, or at lease I don't handle there memory properly:

CGDataProvider: constructor
CGFont: constructor
CTFontCreateWithGraphicsFont: func to convert CGFont to CTFont
CTFontCopyCharacterSet: get a copy of CharacterSet supported by the CTFont

I tried wrap the code with autoreleasepool but did not help.

Please Is there any way to release any allocated memory before continuing the loop to the next font file !!!


Solution

  • Extracting this code from the for loop into another function does the trick of releasing the associated memory with the loaded CGFont and the copied CharacterSet.