用QuarzCore 框架高度定制一個旋鈕渐溶,編譯器報錯:
Mar? 2 13:09:55? AVStudyOne[17578]: CGContextResetState: invalid context 0x170162a00. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
解決方法:
1.Xcode工具欄->Product->Scheme->Edit Scheme->Run->Arguments->Envionment Variables中設置CG_CONTEXT_SHOW_BACKTRACE環(huán)境變量為YES后弄抬,發(fā)現(xiàn)并不能解決問題,只不過編譯日志打印的是其backtrace眉睹。
2.仔細檢查代碼:
CGContextRef context = UIGraphicsGetCurrentContext();進入文檔發(fā)現(xiàn)注釋如下UIKIT_EXTERN CGContextRef __nullable UIGraphicsGetCurrentContext(void) CF_RETURNS_NOT_RETAINED;
意思就是獲取到的CGContext類型的對象竹海,notReitained即在內存管理上其引用計數(shù)并沒有發(fā)生改變。仔細檢查過后發(fā)現(xiàn)bug所在:
CGContextRelease(context);將此句代碼置換為CGContextRestoreGState(context);則編譯日志不會再報錯誤。<前提在之前代碼中用CGContextSaveGState>函數(shù)存儲過context艰争,否則不用做處理。刪除CGContextRelease(context);詞句代碼即可鸠匀。
再次看文檔發(fā)現(xiàn)缀棍,CGContext類型的對象是通過
/* Push a copy of the current graphics state onto the graphics state stack.
Note that the path is not considered part of the graphics state, and is
not saved. */(會將context存儲的到一個狀態(tài)棧上爬范,并不引起引用計數(shù)的變化)
CG_EXTERN void CGContextSaveGState(CGContextRef cg_nullable c)
相應的有一個移出狀態(tài)棧的函數(shù):
/* Restore the current graphics state from the one on the top of the
graphics state stack, popping the graphics state stack in the process. */
CG_EXTERN void CGContextRestoreGState(CGContextRef cg_nullable c)