开发者

Key Value Observing Cascading

Do change notifications cascade with KVO down to their properties or is there any elegant way that does not include implementing it manually by simply observing both parent and child changes?

Let's assume we have a User class and a Document class. One user can have any amount of documents. Now let's assume I have a view controller displaying details about a document and let's also assume I somewhere store a variable called currentUser. If I now observe one document object that belongs to that one user who is also the value of currentUser and I change the currentUser to another u开发者_JAVA百科ser, will the change notification "cascade" down to to that view controller who is only observing the document object that belonged to the previous "currentUser"?


An observer only receives notifications about (specific) properties of (specific) objects it is actually observing. It does not receive notifications about any other changes.

If I understand your description correctly, the observer is observing properties on one particular document object. The observer is not observing the currentUser property (which is part of another object). So no, the observer definitely will not get a notification if currentUser changes.

It is, however, possible in KVO to trigger a change notification for properties that are affected by the change of another property. This is typically used for computed properties:

Imagine a class Event that has a read/write property startDate and endDate, and a computed property duration that calculates the duration based on start and end date:

- (NSTimeInterval)duration
{
    return [[self endDate] timeIntervalSinceDate:[self startDate]];
}

You would set up this class so that it notifies observers of duration when someone modifies startDate or endDate:

+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key
{
    NSSet *keyPaths = [super keyPathsForValuesAffectingValueForKey:key];

    if ([key isEqualToString:@"duration"]) {

        keyPaths = [keyPaths setByAddingObjectsFromSet:
            [NSSet setWithObjects:@"startDate", @"endDate", nil]
        ];

    }

    return keyPaths;
}

This is described in more detail in the Key-Value Observing Programming Guide.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜