Introduction
Welcome to the documentation for the PMKVObserver library. This library provides an easy-to-use key-value observer pattern implementation in Swift.
Features
- Simple and clean Swift syntax
- Observation of key-value changes
- Type-safe and strongly-typed observers
- Supports observation for both properties and subscripted values
- Automatic observation removal on deinit
Installation
You can integrate PMKVObserver into your project using CocoaPods or Swift Package Manager.
CocoaPods
To install PMKVObserver with CocoaPods, add the following line to your Podfile
:
// Podfile
pod 'PMKVObserver'
Then, run the following command:
pod install
Swift Package Manager
To include PMKVObserver in your Swift Package, add the package dependency to your Package.swift
file:
...
dependencies: [
.package(url: "https://github.com/postmates/PMKVObserver.git", .upToNextMajor(from: "1.0.0"))
],
targets: [
.target(name: "YourTarget", dependencies: ["PMKVObserver"])
]
...
Then, run swift build
command to build your package.
Usage
To start observing changes using PMKVObserver, follow these steps:
1. Import PMKVObserver
In your Swift file, import the PMKVObserver module:
import PMKVObserver
2. Create the Observer
Create an instance of PMKVObserver
:
// Example: Observe changes to 'myProperty' on 'myObject'
let observer = PMKVObserver()
3. Start Observing
Start observing the desired key-value path:
observer.observe(object: myObject, keyPath: "myProperty") { newValue, oldValue in
// Handle the value change
print("Value changed from \(oldValue) to \(newValue)")
}
4. Stop Observing
When you no longer need to observe, remove the observation:
observer.invalidate()
Advanced Usage
Observing Multiple Key Paths
To observe multiple key paths, simply call observe
for each key path:
// Observe multiple key paths
observer.observe(object: myObject, keyPath: "property1") { newValue, oldValue in
// Handle the value change for property1
print("Value changed for property1: \(newValue)")
}
observer.observe(object: myObject, keyPath: "property2") { newValue, oldValue in
// Handle the value change for property2
print("Value changed for property2: \(newValue)")
}
Observing Subscripted Values
PMKVObserver also supports observation of subscripted values:
// Observe changes to a subscripted value
observer.observe(object: myObject, keyPath: "subscriptedValues[key]") { newValue, oldValue in
// Handle the value change for the subscripted value
print("Value changed for subscripted value: \(newValue)")
}
Conclusion
Congratulations! You have successfully integrated and used the PMKVObserver library in your Swift project. This powerful library makes key-value observing a breeze in your codebase.