In order to be considered KVO-compliant for a specific property, a class must ensure the following:
- The class must be key-value coding compliant for the property, as specified in Ensuring KVC Compliance.
KVO supports the same data types as KVC, including Objective-C objects and the scalars and structures listed in Scalar and Structure Support.- The class emits KVO change notifications for the property.
- Dependent keys are registered appropriately (see Registering Dependent Keys).
为了使特定属性符合kVO标准,类必须确定以下几点:
- 类的属性必须遵从KVC,如 Ensuring KVC Compliance中所述。
KVO支持与KVC相同的数据类型,包括OC对象和标量和结构体支持中列举的标量和结构体。 - 类会为属性发出KVO变化通知。
- 依赖的key path都被正确注册(参考 Registering Dependent Keys)。
There are two techniques for ensuring the change notifications are emitted. Automatic support is provided by
NSObject
and is by default available for all properties of a class that are key-value coding compliant. Typically, if you follow standard Cocoa coding and naming conventions, you can use automatic change notifications—you don’t have to write any additional code.
有两种技术可以确保发出变化通知。自动支持是由NSObject
提供的,并且对所有遵从KVC的属性都是默认可用的。通常,如果你遵从标准的Cocoa编码和命名约定,就可以使用自动变化通知,不用写额外的代码。
Manual change notification provides additional control over when notifications are emitted, and requires additional coding. You can control automatic notifications for properties of your subclass by implementing the class method automaticallyNotifiesObserversForKey:.
手动更改通知提供了对何时发出通知的额外控制,需要额外的编码。你可以通过实现方法automaticallyNotifiesObserversForKey:来控制子类属性的自动通知。
自动变化通知
NSObject
provides a basic implementation of automatic key-value change notification. Automatic key-value change notification informs observers of changes made using key-value compliant accessors, as well as the key-value coding methods. Automatic notification is also supported by the collection proxy objects returned by, for example,mutableArrayValueForKey:
.
NSObject
提供了自动键-值改变通知的基本实现。自动键值改变通知通过使用键值兼容访问器来通知观察者所做的改变,以及KVC方法。返回的集合代理对象也支持自动通知,例如mutableArrayValueForKey:
.
The examples shown in Listing 1 result in any observers of the property
name
to be notified of the change.
Listing 1的示例会导致属性name
的任何的观察者都会收到改变的通知
Listing 1 Examples of method calls that cause KVO change notifications to be emitted
// Call the accessor method.
[account setName:@"Savings"];
// Use setValue:forKey:.
[account setValue:@"Savings" forKey:@"name"];
// Use a key path, where 'account' is a kvc-compliant property of 'document'.
[document setValue:@"Savings" forKeyPath:@"account.name"];
// Use mutableArrayValueForKey: to retrieve a relationship proxy object.
Transaction *newTransaction = <#Create a new transaction for the account#>;
NSMutableArray *transactions = [account mutableArrayValueForKey:@"transactions"];
[transactions addObject:newTransaction];
手动改变通知
In some cases, you may want control of the notification process, for example, to minimize triggering notifications that are unnecessary for application specific reasons, or to group a number of changes into a single notification. Manual change notification provides means to do this.
在一些情况中,你可能想要控制通知的过程,例如,最小化因应用程序特定的原因不必要的触发通知,或者将多个更改分组到单个通知中。手动改变通知提供了实现这个的方法。
Manual and automatic notifications are not mutually exclusive. You are free to issue manual notifications in addition to the automatic ones already in place. More typically, you may want to completely take control of the notifications for a particular property. In this case, you override the
NSObject
implementation ofautomaticallyNotifiesObserversForKey:
. For properties whose automatic notifications you want to preclude, the subclass implementation ofautomaticallyNotifiesObserversForKey:
should returnNO
. A subclass implementation should invoke super for any unrecognized keys. The example in Listing 2 enables manual notification for thebalance
property, allowing the superclass to determine the notification for all other keys.
手动和自动通知不是互斥的。 除了现有的自动通知之外,您还可以自由发出手动通知。 更典型的是,您可能希望完全控制特定属性的通知。 在这种情况下,您覆盖automaticNotifiesObserversForKey:
的NSObject
实现。 对于要排除自动通知的属性,automaticNotifiesObserversForKey:
的子类实现应返回NO
。 子类实现应该为任何无法识别的键调用super。 Listing 2中的示例启用了balance
属性的手动通知,允许超类确定所有其他键的通知。
Listing 2 Example implementation of automaticallyNotifiesObserversForKey:
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)theKey {
BOOL automatic = NO;
if ([theKey isEqualToString:@"balance"]) {
automatic = NO;
}
else {
automatic = [super automaticallyNotifiesObserversForKey:theKey];
}
return automatic;
}
To implement manual observer notification, you invoke willChangeValueForKey: before changing the value, and didChangeValueForKey: after changing the value. The example in Listing 3 implements manual notifications for the
balance
property.
为了实现手动通知,在改变值之前调用 willChangeValueForKey:,在改变值之后调用 didChangeValueForKey:。Listing 3中的示例实现了balance
属性的手动通知。
Listing 3 Example accessor method implementing manual notification
- (void)setBalance:(double)theBalance {
[self willChangeValueForKey:@"balance"];
_balance = theBalance;
[self didChangeValueForKey:@"balance"];
}
You can minimize sending unnecessary notifications by first checking if the value has changed. The example in Listing 4 tests the value of
balance
and only provides the notification if it has changed.
你可以通过首先检测值是否发生改变来最小化发送不必要的通知。Listing 4中的示例测试了balance
的值并且只有在它改变时才提供通知。
Listing 4 Testing the value for change before providing notification
- (void)setBalance:(double)theBalance {
if (theBalance != _balance) {
[self willChangeValueForKey:@"balance"];
_balance = theBalance;
[self didChangeValueForKey:@"balance"];
}
}
If a single operation causes multiple keys to change you must nest the change notifications as shown in Listing 5.
如果单个操作导致多个键发生了改变,你必须按照Listing 5所示嵌套变化通知。
Listing 5 Nesting change notifications for multiple keys
- (void)setBalance:(double)theBalance {
[self willChangeValueForKey:@"balance"];
[self willChangeValueForKey:@"itemChanged"];
_balance = theBalance;
_itemChanged = _itemChanged+1;
[self didChangeValueForKey:@"itemChanged"];
[self didChangeValueForKey:@"balance"];
}
In the case of an ordered to-many relationship, you must specify not only the key that changed, but also the type of change and the indexes of the objects involved. The type of change is an NSKeyValueChange that specifies
NSKeyValueChangeInsertion
,NSKeyValueChangeRemoval
, orNSKeyValueChangeReplacement
. The indexes of the affected objects are passed as an NSIndexSet object.
在有序的多对多关系情况下,你必须指定更改的键和变化的类型以及相关对象的索引。变化的类型是一个 NSKeyValueChange类型,指定了NSKeyValueChangeInsertion
, NSKeyValueChangeRemoval
, 或 NSKeyValueChangeReplacement
。受影响的对象的索引作为一个NSIndexSet 对象被传递。
The code fragment in Listing 6 demonstrates how to wrap a deletion of objects in the to-many relationship
transactions
.
Listing 6中的代码片段演示了如何在多对多关系事务中包装一个删除事件。
Listing 6 Implementation of manual observer notification in a to-many relationship
- (void)removeTransactionsAtIndexes:(NSIndexSet *)indexes {
[self willChange:NSKeyValueChangeRemoval
valuesAtIndexes:indexes forKey:@"transactions"];
// Remove the transaction objects at the specified indexes.
[self didChange:NSKeyValueChangeRemoval
valuesAtIndexes:indexes forKey:@"transactions"];
}
网友评论