KVO官方文档学习(三)----KVO合规性

官方文档

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 of automaticallyNotifiesObserversForKey:. For properties whose automatic notifications you want to preclude, the subclass implementation of automaticallyNotifiesObserversForKey: should return NO. A subclass implementation should invoke super for any unrecognized keys. The example in Listing 2 enables manual notification for the balance 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, or NSKeyValueChangeReplacement. 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"];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269