天天看點

This class is not key value coding-compliant

xcode的調試視窗,并沒有易懂的錯誤消息。那是因為沒有異常被抛出。在xcode告訴你異常的原因之前,Exception Breakpoint已經暫停了這個程式。有些時候你會從Exception Breakpoint得到一些局部的錯誤消息,但是有些時候就得不到。

為了得到全部的錯誤消息,點選調試器工具欄上的“Continue Program Execution”按鈕:

This class is not key value coding-compliant

你可能需要點選好幾次才可以,然後你将會得到錯誤消息:

  1. Problems[14961:f803] *** Terminating app due to uncaught exception 'NSUnknownKeyException',
  2. reason: '[ setValue:forUndefinedKey:]: this class is not
  3. key value coding-compliant for the key button.'
  4. *** First throw call stack:
  5. (0x13ba052 0x154bd0a 0x13b9f11 0x9b1032 0x922f7b 0x922eeb 0x93dd60 0x23091a 0x13bbe1a
  6. 0x1325821 0x22f46e 0xd6e2c 0xd73a9 0xd75cb 0xd6c1c 0xfd56d 0xe7d47 0xfe441 0xfe45d
  7. 0xfe4f9 0x3ed65 0x3edac 0xfbe6 0x108a6 0x1f743 0x201f8 0x13aa9 0x12a4fa9 0x138e1c5
  8. 0x12f3022 0x12f190a 0x12f0db4 0x12f0ccb 0x102a7 0x11a9b 0x2872 0x27e5)
  9. terminate called throwing an exception

就像之前的一樣,你可以忽略下面的那些數字。他們展示了調用堆棧,但是在調試導航器的左邊有更加直覺的堆棧調用展示。

有趣的部分是:

NSUnknowKeyException

MainViewController

“this class is not key value coding-compliant for the key button”

這個異常的名字為NSUnknownKeyException,它是這個錯誤很好的訓示器。它告訴你在某個地方有一個“unknown key”。這個某一個地方通常就是MainViewController,并且這個key就是“button”。

既然我們已經确定了,所有這些都是發生在裝載nib的時候。這個應用使用的是storyboard,而不是nib檔案,但是其實storyboard内部就是nib的集合(也就是可以有很多的nib),是以這個錯誤就在這個storyboard中。

檢查一下MainViewController的outlets:

This class is not key value coding-compliant

在Connections Inspector(連接配接檢測器)裡,你可以看見在viewcontroller中間的UIButton是連接配接到MainViewController的“button”outlet上的。是以storyboard引用了一個名叫“button”的outlet,但是通過這個錯誤消息說明它找不到這個outlet。

讓我們來看看MainViewController.h:

  1. @interface MainViewController : UIViewController
  2. @property (nonatomic, retain) NSArray *list;
  3. @property (nonatomic, retain) IBOutlet UIButton *button;
  4. - (IBAction)buttonTapped:(id)sender;
  5. @end

這裡是為這個“button”定義了外部連接配接屬性的(@property),是以這個問題是什麼呢?假如你仔細觀察了編譯警告的話,你可以已經知道是什麼地方的問題了。

假如還不知道的話,檢查一下MainViewController.m的@synthesize的内容的話。你現在看出問題沒有啊?

這個代碼其實沒有@synthesize這個button的屬性。它(@synthesize)其實是告訴MainVIewController他自己有個“button”的屬性,提供一個背景執行個體變量,并且提供getter和setter方法(這就是@synthesize所做的)。

把下面的增加到MainViewController.m裡面已經存在的@synthesize行的下面來修複這個問題:

  1. @synthesize button = _button;

現在這個app應該不會在你運作的時候崩潰了!

注意:“this class is not key value coding-compliant for the key XXX”的錯誤經常都是由于你裝載這個nib,但是裡面引用的一些熟悉可能不存在。特别是當你在代碼中移除了outlet屬性後,但是你卻沒有在nib中移除這個連接配接。

【原文:http://article.ityran.com/archives/1006】