本篇文章主要介绍了"KVO Considered Harmful ---Soroush Khanlou",主要涉及到corners,require,Dictionary方面的内容,对于移动开发感兴趣的同学可以参考一下:
KVO Considered HarmfulI would normally title this something more clever, but I w...
[_tableView removeObserver:self forKeyPath:NSStringFromSelector(@selector(contentSize)) context:NULL];
Now, this isn’t strictly necessary, since the table view will probably get deallocated also, and won’t be able to fire any more notifications. Nevertheless, we should take care of this. An important thing to note is that KVO will throw an exception and crash our app if we try to remove the same observance twice. What happens if a superclass were also observing the same parameter on the same object? It would get removed twice, and the second time would cause a crash.
Hm. Maybe this is where the context
parameter comes in? That would make sense. We could pass a context
like self
, which would make perfect sense, since this object is the context. However, this wouldn’t help us in the superclass case (since self
would point to the same object in the superclass as well as the subclass). Mattt Thompson at NSHipster recommends using a static pointer that stores its own value for the context, like so:
static void *ClassNameTableViewContentSizeContext = &ClassNameTableViewContentSizeContext;
This should be scoped to our file, so that no other files have access to it, and we use a separate one for each key-value observation we do. This helps to make sure that none of our super- or subclasses can deregister us from being an observer.
We can use this context when registering and then also check it in the observation method. Now that we have contexts, we only want to pass the notification along to super if we didn’t use it ourselves. One nice thing about having a pointer that is specific to this one exact observance is that we can check just this parameter, instead of having to check the object
and keypath
parameters, simplifying our code.