KVC and Outlets

来源:互联网 发布:中国科技大学知乎 编辑:程序博客网 时间:2024/04/28 08:15

Key–value coding lies at the heart of how outlet connections work (Chapter 7). The name of the outlet in the nib is a string. Key–value coding turns the string into a hunt for appropriate accessors.

Suppose you have a class MyClass with an instance variable myVar, and you’ve drawn a myVar outlet from that class’s representative in the nib to a MyOtherClass nib object. When the nib loads, the outlet name myVar is translated to the accessor method name setMyVar:, and your MyClass instance’s setMyVar: method, if it exists, is called with the MyOtherClass instance as its parameter, thus setting the value of your MyClass instance’s myVar instance variable to the MyOtherClass instance (Figure 7-7).

If something goes wrong with the match between the outlet name in the nib and the name of the instance variable or accessor in the class, then at runtime, when the nib loads, Cocoa will attempt to use key–value coding to set a value in your object based on the name of the outlet, will fail, and will generate an exception, complaining that the class is not key–value coding compliant for the key (the outlet name) — that is, your app will crash at nib-loading time. A likely way for this to happen is that you form the outlet correctly but then later change the name of (or delete) the instance variable or accessor in the class (seeMisconfiguring an Outlet).

Conversely, you should not use accessor names for methods that aren’t accessors. For instance, returning to our example with MyClass and myVar, you probably would not want MyClass to have a method called setMyVar: if it is not the accessor for myVar. If it did have such a method, it would be called when the nib loads and key–value coding tries to resolve themyVar outlet in the nib. The MyOtherClass instance would be passed to this method, so there’s no error, but the MyOtherClass instance wouldnot be assigned to the myVar instance variable, because setMyVar: isn’t its accessor. As a result, references in your code to myVar would be references to nil. The setMyVar: method has acted as a falsefaçade, preventing the myVar instance variable from being set at nib-loading time. Making this kind of mistake is surprisingly common.

原创粉丝点击