Question

Apple's Core Data Utility Tutorial recommends implementing setNilValueForKey:and testing its effect:

Use key-value coding to set the process ID to nil. Build and run the utility. Again, what happens? And finally, comment out the setNilValueForKey: method and test once more.

I attempt to set the process ID to nil with this code: [run setValue:nil forKey:@"processID"]; but this doesn't call setNilValueForKey:. Why not?

Here's my implementation; the NSLog statement I added never appears.

- (void) setNilValueForKey:(NSString*)key {
    NSLog(@"setNilValueForKey: %@",  key) ;
    if ( [key isEqualToString:@"processID"] ) {
        [self setValue:@0  forKey:key ] ;
    }
    else {
        [super setNilValueForKey:key] ;
    }
}

I found similar stackoverflow discussions, but none answer this question.

Was it helpful?

Solution

It seems that setNilValueForKey: is never called if the dynamically generated accessor methods are used.

If you provide a custom setter method for the "processID" property in "Run.m":

- (void)setProcessID:(NSInteger)processID
{
    [self willChangeValueForKey:@"processID"];
    [self setPrimitiveValue:@(processID) forKey:@"processID"];
    [self didChangeValueForKey:@"processID"];
}

then

[run setValue:nil forKey:@"processID"]

causes setNilValueForKey: to be called.

That is only what I experienced by try and error, I do not have official references for this. But the "Core Data Utility Tutorial" exists since Mac OS X 10.4, where dynamically generated accessor methods (as far as I know) did not yet exist. So it could be that the parts about setNilValueForKey: where not updated for 10.5. But that is pure guessing on my side.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top