The source code

FBKVOController

KVO is a very useful technique for communicating between layers in a model-view-controller application. FBKVOController encapsulates the system’s KVO by providing a simple, modern API that is also thread-safe. The benefits include

  • Use the block callback, custom actions, and the original NSKeyValueObserving callback
  • Implement automatic removal of the observer, no need to develop the manual removal
  • Thread safety
  • With the block form, the code is more centralized.

Use the API

Step 1: Define a mediator, kVO controller. Step 2: add observations

- (FBKVOController *)kvoCtrl{
    if(! _kvoCtrl) { _kvoCtrl = [FBKVOController controllerWithObserver:self]; }return _kvoCtrl;
}

[self.kvoCtrl observe:self.person keyPath:@"name" options:(NSKeyValueObservingOptionNew) block:^(id  _Nullable** observer, id _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {

        NSLog(@"% @",change);

    }];
Copy the code

Source code analysis

Intermediate initialization method:

FBKVOController controllerWithObserver:self]

  1. Weak references hold self
  2. Initialize aNSMapTableTable, this table mainly storesobjectkvo infosCorresponding information

Adding an Observer

Let’s take block as an example. The other ways are the same

  1. Let’s create a_FBKVOInfoInstance, let after judgmentobjectInfosMapDid it exist before? ThisinfoInstance, added if it does not exist

2. Register the system observer in a single column

[[_FBKVOSharedController sharedController] Observe: Object Info :info] Some status judgments are made. If the status is not registered, it will be removed.

The callback processing

In the system method, do the following processing:

If it isblockWay,blockCallback, if customactions, the custom action is called, or the system’s if the system’s callback method is implemented.

Remove the watch

Vc holds the FBKVOController object, and when VC releases its control it calls vc’s dealloc, and it also calls the FBKVOController object dealloc, and if you remove an observer from that, it doesn’t have to be removed from each controller.

- (void)dealloc
{
  [self unobserveAll];
  pthread_mutex_destroy(&_lock);
}
Copy the code

As expected, the FBKVOController removes the observer.

conclusion

By reading the source code of FBKVOController, we can mainly understand a design pattern, which will have some inspiration for our business development design.