Search code examples
iosmemory-leakscore-text

CTFramesetterCreateWithAttributedString cause memory leak


I don't know why this simple piece of code can cause memory leak sometimes (not always).

This piece of code is wrapped in an NSOperation and runs in an NSOperationQueue queue. The operation will trim sourceNSAString to fit in some size and return it to some other thread as a result.

//sourceNSAString is a NSMutableAttributedString that will be set to nil elsewhere in another GCD queue.
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef) sourceNSAString); 

if (frameSetter) {

    CFRange fitRange = {static_cast<CFIndex>(range.location), 0};

    CFRange totalRange = {static_cast<CFIndex>(range.location), static_cast<CFIndex>(range.length)};

    CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(frameSetter, totalRange, NULL, size, &fitRange);

    CFRelease(frameSetter);

      ...... trim sourceNSAString to fit in fitRange
 }

Is it because: 1, I should not return sourceNSAString to another thread ? or 2, CTFramesetterCreateWithAttributedString can't be used in background thread ?

Any ideas? Thanks!


Solution

  • OK, it seems that it's a simulator bug (at least for now). I profiled my App on a device and the memory leak just disappeared. Simulator seems to have a lot of memory leaks when using core text in multi-thread environment. For example, create a CTFrameSetter and release it in the same GCD serial queue later (which is allowed according to the Doc) can cause memory leak randomly. Anyway all those memory leaks just go away when profiled in a real device.