xcode的调试窗口,并没有易懂的错误消息。那是因为没有异常被抛出。在xcode告诉你异常的原因之前,Exception Breakpoint已经暂停了这个程序。有些时候你会从Exception Breakpoint得到一些局部的错误消息,但是有些时候就得不到。
为了得到全部的错误消息,点击调试器工具栏上的“Continue Program Execution”按钮:
你可能需要点击好几次才可以,然后你将会得到错误消息:
- Problems[14961:f803] *** Terminating app due to uncaught exception 'NSUnknownKeyException',
- reason: '[ setValue:forUndefinedKey:]: this class is not
- key value coding-compliant for the key button.'
- *** First throw call stack:
- (0x13ba052 0x154bd0a 0x13b9f11 0x9b1032 0x922f7b 0x922eeb 0x93dd60 0x23091a 0x13bbe1a
- 0x1325821 0x22f46e 0xd6e2c 0xd73a9 0xd75cb 0xd6c1c 0xfd56d 0xe7d47 0xfe441 0xfe45d
- 0xfe4f9 0x3ed65 0x3edac 0xfbe6 0x108a6 0x1f743 0x201f8 0x13aa9 0x12a4fa9 0x138e1c5
- 0x12f3022 0x12f190a 0x12f0db4 0x12f0ccb 0x102a7 0x11a9b 0x2872 0x27e5)
- 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:
在Connections Inspector(连接检测器)里,你可以看见在viewcontroller中间的UIButton是连接到MainViewController的“button”outlet上的。因此storyboard引用了一个名叫“button”的outlet,但是通过这个错误消息说明它找不到这个outlet。
让我们来看看MainViewController.h:
- @interface MainViewController : UIViewController
- @property (nonatomic, retain) NSArray *list;
- @property (nonatomic, retain) IBOutlet UIButton *button;
- - (IBAction)buttonTapped:(id)sender;
- @end
这里是为这个“button”定义了外部连接属性的(@property),因此这个问题是什么呢?假如你仔细观察了编译警告的话,你可以已经知道是什么地方的问题了。
假如还不知道的话,检查一下MainViewController.m的@synthesize的内容的话。你现在看出问题没有啊?
这个代码其实没有@synthesize这个button的属性。它(@synthesize)其实是告诉MainVIewController他自己有个“button”的属性,提供一个后台实例变量,并且提供getter和setter方法(这就是@synthesize所做的)。
把下面的增加到MainViewController.m里面已经存在的@synthesize行的下面来修复这个问题:
- @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】