您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 6 上的怪異崩潰:_UIRecordArgumentOfInvocationAtIndex 例外排查

編輯:iOS 開發綜合

遇到的問題

下面兩段自訂 UIBarButtonItem 的程式碼,在 iOS 7 上完全正常:

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil]
    setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor darkGrayColor]}
                 forState:UIControlStateNormal];
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil]
    setTitleTextAttributes:@{@"UITextAttributeTextColor" : [UIColor darkGrayColor]}
                 forState:UIControlStateNormal];

但在 iOS 6 上,只要開啟某些系統內建的 view controller(例如預覽 PDF 的 QLPreviewController),就會遇到 _UIRecordArgumentOfInvocationAtIndex 例外而崩潰。

查了 StackOverflow 上類似案例後可以確認,這是 iOS SDK 本身的問題—— Питання出在 UIAppearance 的 iOS 6 實作上。當你在全域設定 appearance 的外觀屬性,而某個系統 view controller 內部又要配置自己的 bar button item 時,這套外觀代理的訊息轉發機制就會拿到型別不符的參數,進而觸發例外。

解法

改用以下寫法即可避開:

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil]
    setTitleTextAttributes:@{UITextAttributeTextColor : [UIColor darkGrayColor]}
                 forState:UIControlStateNormal];

差別在於 key 的形式:直接寫 UITextAttributeTextColor 這個未加引號的識別符,而不是 @"UITextAttributeTextColor" 字串,也不要用 NSForegroundColorAttributeName。前者走的是舊版的 UIAppearance 訊息路徑,能正確處理型別;後兩者在新版路徑下會引發上述例外。

從這件事可學到的教訓

  • 全域 appearance 是雙面刃。用 appearance 或 appearanceWhenContainedIn: 設定的樣式會套用到全 App 所有符合條件的元件,包含系統 framework 內部產生的那些。若某個系統畫面 crash 得莫名其妙,第一步該懷疑的就是這裡。
  • 盡量縮小作用範圍。比起全域設定,直接對具體的 bar button item 實例設定 setTitleTextAttributes:forState: 更安全,也更容易除錯。
  • 舊 API 與新 API 不要混用。iOS 7 之後蘋果把屬性名稱改了(UIKit 屬性 vs 字串 key),兩套並存期間混用是問題的溫床。若專案仍需支援 iOS 6,用 NSFoundationVersionNumber_iOS_7_0 或 __IPHONE_7_0 巨集分別處理兩個版本最保險。

這類小插曲偶爾會出現,但把原因搞清楚之後,往往也是對 Cocoa Touch 內部機制理解更深一層的機會。

參考網址

  • https://stackoverflow.com/questions/14125378/uiappearence-support-for-ios-6-unexpected-results
  • https://stackoverflow.com/questions/19863972/mfmailcomposeviewcontroller-crashes-because-of-global-appearance-properties-on-i
  • https://stackoverflow.com/questions/22489828/adbannerview-crashes-app-when-it-is-clicked
  • https://stackoverflow.com/questions/12567708/monotouch-ios-6-crash-when-using-mfmailcomposeviewcontroller
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved