簡體   English   中英

調用CGImage時執行EXEC_BAD_ACCESS

[英]EXEC_BAD_ACCESS on calling CGImage

我有以下代碼:

UIImage *img = [UIImage imageNamed:@"BRBlueCircleMask"];
CGImageRef activeCirleMaskImage = img.CGImage;
activeCirleMaskLayer = [CALayer layer];
activeCirleMaskLayer.frame = CGRectMake(0, 0, 50, 50);
activeCirleMaskLayer.contents = CFBridgingRelease(activeCirleMaskImage);

EXEC_BAD_ACCESS在第二行發生70%的時間(即有時正常工作)。 怎么了?

從此代碼段中看不出問題,即使圖像無法加載(圖像引用最終將為NULL),該代碼段也可以正常工作。

您可能在其他地方以這種方式表現出內存管理問題,並且/或者調試器對崩潰的位置感到困惑。

如下更改您的代碼(此外,我假設您正在使用ARC)。 首先,我將在現有代碼中添加注釋,然后向您展示如何解決您的問題

// While this is a strong reference, ARC can release it after 'img.CGImage' (I have an accepted bug on this)
UIImage *img = [UIImage imageNamed:@"BRBlueCircleMask"];
// ARC should cause 
CGImageRef activeCirleMaskImage = img.CGImage;
 // you do not own the image, and a current ARC bug causes this object SOMETIMES to get released immediately after the assignment!!!
activeCirleMaskLayer = [CALayer layer];
activeCirleMaskLayer.frame = CGRectMake(0, 0, 50, 50);
activeCirleMaskLayer.contents = CFBridgingRelease(activeCirleMaskImage); // You are releasing an object here you don't own, which is the root cause of your problem

如下更改代碼

UIImage *img = [UIImage imageNamed:@"BRBlueCircleMask"];
// want to get the CGImage copied ASAP
CGImageRef activeCirleMaskImage = CGImageCreateCopy(img.CGImage); // now you own a copy
activeCirleMaskLayer = [CALayer layer];
activeCirleMaskLayer.frame = CGRectMake(0, 0, 50, 50);
activeCirleMaskLayer.contents = CFBridgingRelease(activeCirleMaskImage); // OK now, its your copy

PS:如果有人認為CGImage的激進發行不是真實的,我很樂意發布我的錯誤報告(以及演示實際問題的演示項目)

編輯:蘋果已修復此問題,我相信它是在iOS6中。 現在,它們跟蹤內部指針的使用並推遲釋放內存,直到該指針超出范圍。 修復程序是在定義SDK和標頭的情況下進行的,因此您需要鏈接到iOS6或7-可能還不確定該的部署目標。

暫無
暫無

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

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