KVC and Outlets

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值