Search code examples
iosobjective-ckey-value-observing

KVO not working for Categories


I try to add a property to a class using a category. The property accessors look something like:

- (NSArray *)thumbnails {
    return objc_getAssociatedObject(self, kThumbnails);
}

- (void)setThumbnails:(NSArray *)thumbnails {
    [self willChangeValueForKey:@keypath(self.thumbnails)];
    objc_setAssociatedObject(self, kThumbnails, thumbnails, OBJC_ASSOCIATION_RETAIN);
    [self didChangeValueForKey:@keypath(self.thumbnails)];
}

Unfortunately no notification is triggered. Is it even possible to add KVO compliant properties to categories?


Solution

  • KVO is definitely possible with accessor methods in categories.

    The posted code is KVO compliant for the key @"thumbnails". You should not even have to send the willChangeValueForKey: and didChangeValueForKey: messages.