ZHObserverSwift
An easy way in Swift to use KVO, prefer block.
If your have any question, you can email me(zhangbozhb@gmail.com) or leave message.
Requirements
- iOS 8.0+
- Xcode 7.0 or above
Usage
KVO ZHObserver way
- add observe
obj.zh_observe("your path", options: .New) { (object, values, change) in
// your code
}
- remove observe
obj.zh_unobserve("your path") // remove specified observed path, and do not wrong about "your path" has oberserved
obj.zh_unobserve(nil) // remove all observed path
Instead of the familiar syntax like:
obj.addObserver(observerObj, forKeyPath: "your path", options: .New, context: &yourContext)
...
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard context == &yourContext else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
return
}
if keyPath == ""your path" {
// your code
}
}
...
obj.removeObserver("your path") // you have to care "your path" if not observed it will crash
Installation
CocoaPods
CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:
$ gem install cocoapods
To integrate ChameleonSwift into your Xcode project using CocoaPods, specify it in your Podfile
:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'ZHObserverSwift'
If you use swift 2, use pod 'ZHObserverSwift' , '~> 0.1'
Then, run the following command:
$ pod install
You should open the {Project}.xcworkspace
instead of the {Project}.xcodeproj
after you installed anything from CocoaPods.
Carthage
github "zhangbozhb/ZHObserverSwift"