1. 程式人生 > >iOS指南系列:如何解決奔潰問題-關於記憶體訪問續

iOS指南系列:如何解決奔潰問題-關於記憶體訪問續

Push the Button

現在的應用程式工程 - 或者至少是沒有問題的開始 - 點選該按鈕執行

The app finally starts up.

Woah! 程式又崩潰了 SIGABRT ,還在 main.m

除錯窗格錯誤訊息

Problems[6579:f803] -[MainViewController buttonTapped]: unrecognized selector sent
to instance 0x6e44850

堆疊跟蹤不是太清晰,它列出了一大堆有關單程或其他傳送事件執行行動方法,但你已經知道行動參與畢竟你可以找到一稱為IBAction方法的UIButton結果。可以看到NSobject Performaselector執行了一個方法:


當然,你見過這個錯誤訊息。”一種方法被稱為不存在的“這一次目標物件MainViewController看起來是正確的操作方法之一,因為通常包含按鈕檢視控制器如果MainViewController.hIBAction方法也確實是存在的

- (IBAction)buttonTapped:(id)sender;

我們可以和之前的步驟一樣,繼續點選執行,直到錯誤被完全丟擲:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MainViewController buttonTapped]: unrecognized selector sent to instance 0x6b4b1f0'

這次看到多一個資訊,引數不合法! 或者說問題就是錯誤訊息方法的名稱buttonTappedMainViewController方法命名buttonTapped:,注意在最後一個冒號因為這個方法接受一個引數名為“sender”另一方面錯誤資訊方法的名稱,包括冒號,因此不帶任何引數該方法簽名,而似乎看起來像這樣
- (IBAction)buttonTapped;
這裡發生了什麼最初的方法沒有引數的定義方式,也允許的操作方法。而且連線觸控按鈕的內部事件和storyboard的button時候,似乎就是沒有引數的方式然而一段時間
該方法的簽名被更改,包括“sender”引數沒有更新相應的sences
你可以看到的storyboard按鈕連線inspector(MainviewController-buttontapped)

The button's connections in the storyboard.

首先斷開觸控內部事件(點選小X然後將它連線主檢視控制器,但這個時候選擇buttonTapped方法是現有的。連結後,注意連線inspector,現在 方法的名稱後有個小冒號(表明是帶引數的)
執行的應用程式點選按鈕什麼?在main函式中,你又得到無法識別的selector”的訊息雖然這一次正確識別作為buttonTapped:的 方法

Problems[6675:f803] -[MainViewController buttonTapped:]: unrecognized selector sent
to instance 0x6b6c7f0

If you look closely, the compiler warnings should point you to the solution again. Xcode complains that the implementation of MainViewController is incomplete. Specifically, the method definition for buttonTapped:is not found.

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MainViewControllerbuttonTapped:]: unrecognizedselector sent to instance 0x6d37a00'

Xcode shows an incomplete implementation warning.

輪到檢查 MainViewController.m. 看起來似乎有定義(我也沒有發現這個拼寫錯誤) buttonTapped: 但是等一下… 好像不對頭啊:

- (void)butonTapped:(id)sender

很容易解決,修改下:

- (void)buttonTapped:(id)sender

注意,這裡就沒有必要申明為IBAction, 如果你願意,當然也可以!

Note: This sort of thing is easy to catch if you’re paying attention to the compiler warnings. Personally, I treat all warnings as fatal errors (there is even an option for this in the Build Settings screen in Xcode) and I’ll fix each and every one of them before running the app. Xcode is pretty good at pointing out silly mistakes such as these, and it’s wise to pay attention to these hints.

我的一個結論: 1. 絕對重視編譯錯誤,fix他們 2. 多閱讀程式碼 3. 把告警的地方的資訊展開,看詳細內容  忘了:檢查inspector/outlet/view/event connection