We analyzed the KVO principle in the KVO analysis (1) of the underlying principle of iOS above, and this paper mainly defines the implementation of KVO according to the KVO principle.

Define managementKVOInformation of the class

Define management KVO class information, mainly including the Observer, keyPath, NSKeyValueObservingOptions and monitored properties change callback block, for example, this paper takes SafeKVOInfoManager class for class management, the code is as follows

  • .h code
  • The m code

KVOProcessing classKey points and difficulties

To make our custom KVO available to all classes that inherit from NSObject, the KVO processing class handles the classification of NSObject. This paper uses NSObject+SafeKVO classification as the KVO processing class.

NSObject+SafeKVOClassification declaration function

safeAddObserver:Function analysis

We add attributes to any objectKVOListen, both need to be calledsafeAddObserver:function

judgeSetterMethodFromeKeyPathFunction analysis

setterForGetterfunction

There are also getters that get from setter methodsgetterForSetter

Derived functioncreatSafeKVONotifingObservingKVOWithKeyPathAnalysis of the

safe_classFunction analysis

safe_setterFunction analysis

safe_deallocAnalysis of the

safe_deallocAnalysis of results after operation

safeRemoveObserverFunction analysis

safeRemoveObserverFunctions can be called differently

Git project download address