簡體   English   中英

CTFramesetterCreateWithAttributedString導致內存泄漏

[英]CTFramesetterCreateWithAttributedString cause memory leak

我不知道為什么這段簡單的代碼有時會導致內存泄漏(並非總是如此)。

這段代碼包裝在NSOperation中,並在NSOperationQueue隊列中運行。 該操作將修剪sourceNSAString使其適合某個大小,然后將其返回到其他某個線程。

//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
 }

是因為:1,我不應該將sourceNSAString返回到另一個線程嗎? 還是2,CTFramesetterCreateWithAttributedString不能在后台線程中使用?

有任何想法嗎? 謝謝!

好的,這似乎是模擬器錯誤(至少現在是這樣)。 我在設備上分析了我的應用程序,而內存泄漏剛剛消失了。 在多線程環境中使用核心文本時,模擬器似乎有很多內存泄漏。 例如,創建一個CTFrameSetter並在以后在同一GCD串行隊列中釋放它(根據Doc的允許)可能會隨機導致內存泄漏。 無論如何,在真實設備中進行分析時,所有這些內存泄漏都會消失。

此泄漏不僅是模擬器錯誤,它還會顯示在實際設備上。 請參閱我對這個相關問題的答案以進行深入調試, 隨着CTFontCreateWithName和CTFramesetterRef的使用,內存使用量會增加

我認為您應該在if語句之后釋放frameSetter,因為如果不執行if語句,frameSetter不會被釋放。

    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);

這應該工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM