If I wanted to write my own setter method corresponding to KVO, would it look something like this?

- (void)setFirstName:(NSString*)firstNameValue {
    [self willChangeValueForKey:@"firstName"];
    [firstName release];
    firstName = firstNameValue;
    [firstName retain];
    [self didChangeValueForKey:@"firstName"];
}

It is right? So, the willChange ... foobar didChange ... element is blocking the KVO notification?

+3
source share
2 answers

No, your implementation is not 100% correct. Think about what happens if firstName is currently set to an NSString instance and the setter is called with that very same instance. First, you free the instance, than you set the instance variable, which in this case does not change anything, and you try to save the instance, but by then it may well be canceled already.

It should be:

- (void)setFirstName:(NSString*)firstNameValue {
    [self willChangeValueForKey:@"firstName"];
    [firstNameValue retain];
    [firstName release];
    firstName = firstNameValue;
    [self didChangeValueForKey:@"firstName"];
}

or

- (void)setFirstName:(NSString*)firstNameValue {
    if (firstNameValue != firstName) {
        [self willChangeValueForKey:@"firstName"];
        [firstName release];
        firstName = firstNameValue;
        [firstName retain];
        [self didChangeValueForKey:@"firstName"];
    }
}

, , -, .

+12

- didChangeValueForKey: , .

0

Source: https://habr.com/ru/post/1748999/


All Articles