Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic Key-Value Observing in Cocoa

As I learn more about KVO and KVC, I have become curious -

How does NSObject provide automatic KVO when accessing setter methods?

If I create a new object with an accessor named setName,

how does an observer get notified when someon calls

[obj setName:@"Mystery"];

Thanks for any feedback

like image 935
OptimisticMonkey Avatar asked Dec 23 '22 09:12

OptimisticMonkey


1 Answers

I always explain to people that "nothing is magic in Cocoa; it's just code." But KVO borders on magic. It's called isa-swizzling. Your class is transformed at runtime (the first time anyone observes you) into a dynamically generated sub-class that overloads all getters and setters. Calls to -class are wired to lie to you and return the old class, so you won't see the magic subclasses except in the debugger if you look directly at the isa pointer.

Noticing that KVO must be bizarre is a major step in Cocoa enlightenment. Congratulations.

Key-Value Observing Implementation Details

like image 50
Rob Napier Avatar answered Mar 07 '23 00:03

Rob Napier