Key-Value Observing Affected Keys

I like to write handy names for my properties like so:

@property (nonatomic, assign, getter = isLoading) BOOL loading;

As you can see I’ve defined a special name for the getter: isLoading.

There’s only one problem with this:

If another class is observing this class key path loading, it won’t get notified about changes, unless you overwrite your setter like so:

- (void)setLoading:(BOOL)loading
    [self willChangeValueForKey:NSStringFromSelector(@selector(isLoading))];
    _loading = loading;
    [self didChangeValueForKey:NSStringFromSelector(@selector(isLoading))];

Yesterday I stumbled upon a new way to solve this and a very related problem if different keys are affecting each other.

Registering Dependent Keys

You can implement a class method that follows the naming convention keyPathsForValuesAffecting<Key> to trigger notifications automatically for a (to-one relationship to a) dependent keyPath.

The above snippet could be abandoned using the following implementation:

+ (NSSet *)keyPathsForValuesAffectingIsLoading 
    return [NSSet setWithObjects:NSStringFromSelector(@selector(isLoading)), nil];

As you can see, the above method returns an instance of NSSet, allowing to specify a bunch of dependent properties that might change dependently.

Here’s the link to the Apple documentation on this topic: Key-Value Observing Programming Guide