本篇文章主要介绍了"KVO Considered Harmful ---Soroush Khanlou",主要涉及到corners,require,Dictionary方面的内容,对于移动开发感兴趣的同学可以参考一下:
KVO Considered HarmfulI would normally title this something more clever, but I w...
KVO Considered Harmful
I would normally title this something more clever, but I want this post to be findable by people who are looking for exactly this. Thus, we stick to the convention.
KVO, or key-value observing, is a pattern that Cocoa provides for us for subscribing to changes to the properties of other objects. It’s hands down the most poorly designed API in all of Cocoa, and even when implemented perfectly, it’s still an incredibly dangerous tool to use, reserved only for when no other technique will suffice.
What makes KVO so bad?
I want to run through a few ways that KVO is really problematic, and how problems with it can be avoided. The first and most obvious problem is that KVO has a truly terrible API. This manifests itself in a few ways:
KVO all comes through one method
Let’s say we want to observe the contentSize
of our table view. This seems like a great use for KVO, since there’s no other way to get at the information about this property changing. Let’s get started. To register for updates on an object’s property, we can use this method:
- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
Seems simple enough, self
is the observer
and the keyPath
is contentSize
. No clue what those other parameters do, so let’s leave them alone for now.
[_tableView addObserver:self forKeyPath:@"contentSize" options:0 context:NULL];
Great. Now let’s respond to this change: