Key Value Observing - how to observe all the properties of an object?

前端 未结 2 1243
故里飘歌
故里飘歌 2020-12-14 03:13

I am happy with the use of Key Value Observing (KVO), and how to register to receive notifications of property change:

[account addObserver:inspector
                


        
2条回答
  •  情歌与酒
    2020-12-14 03:21

    The following Swift code adds observations for each property, as suggested by david van brink. It has an additional function to remove the observations (eg in deinit):

    extension NSObject {
        func addObserverForAllProperties(
            observer: NSObject,
            options: NSKeyValueObservingOptions = [],
            context: UnsafeMutableRawPointer? = nil
        ) {
            performForAllKeyPaths { keyPath in
                addObserver(observer, forKeyPath: keyPath, options: options, context: context)
            }
        }
    
        func removeObserverForAllProperties(
            observer: NSObject,
            context: UnsafeMutableRawPointer? = nil
        ) {
            performForAllKeyPaths { keyPath in
                removeObserver(observer, forKeyPath: keyPath, context: context)
            }
        }
    
        func performForAllKeyPaths(_ action: (String) -> Void) {
            var count: UInt32 = 0
            guard let properties = class_copyPropertyList(object_getClass(self), &count) else { return }
            defer { free(properties) }
            for i in 0 ..< Int(count) {
                let keyPath = String(cString: property_getName(properties[i]))
                action(keyPath)
            }
        }
    }
    

提交回复
热议问题