KVO
KVO(Key-value observing)是cocoa編程模式中的一種通知機(jī)制,其主要用來觀察一個(gè)對象屬性變化。KVO在變化分層設(shè)計(jì)中是最常用,比如說MVC中的model和views之間通信。
Objective-C
KVO在Objective-C中的使用時(shí)需要三個(gè)步驟,首先
1. Register
- (void)addObserver:(NSObject *)observer
forKeyPath:(NSString *)keyPath
options:(NSKeyValueObservingOptions)options
context:(void *)context;
2. ObserverValueChange
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSKeyValueChangeKey, id> *)change
context:(void *)context;
3. RemoveObserver
- (void)removeObserver:(NSObject *)observer
forKeyPath:(NSString *)keyPath;
Swift
在swift中,如果想類的屬性支持KVO,需要將屬性用@objc和dynamic修飾。如下:
class MyObjectToObserve: NSObject {
@objc dynamic var age = 24
func updateAge() {
age += 1
}
}
區(qū)別于Objective-C中的register、valueChange、remove等方法實(shí)現(xiàn)在不同的位置。swift的KVO實(shí)現(xiàn)在方法observe(_:options:changeHandler:)執(zhí)行以上操作。
class MyObserver: NSObject {
@objc var objectToObserve: MyObjectToObserve
var observation: NSKeyValueObservation?
init(object: MyObjectToObserve) {
objectToObserve = object
super.init()
observation = observe(\.objectToObserve.age,
options: [.old, .new],
changeHandler: { (object, change) in
print("去年年齡: \(change.oldValue!), 今年年齡: \(change.newValue!)")
})
}
}
初始化需要觀察的對象:
let observerd = MyObjectToObserve()
let observer = MyObserver(object: observed)
observed.updateAge() // 觸發(fā)屬性值的變化
// 去年年齡: 24, 今年年齡: 25
可以看到,swift下使用KVO,不用主動調(diào)用removObserver方法,從而降低了Objective-C中忘記調(diào)用而導(dǎo)致的crash,并且keypath和是一一對應(yīng)的。
Singleton
單例也是UI開發(fā)中分常用的設(shè)計(jì)模式。swift中單例區(qū)別于Objective-C中的實(shí)現(xiàn),使用static關(guān)鍵字修飾屬性。
class Singleton {
static let sharedInstance = Singleton()
}
如果需要在初始化類之前初始一些邊來個(gè),需要采用下面的方法:
class Singleton {
static let sharedInstance: Singleton {
let instance = Singleton()
// 初始化代碼
return instance
}()
}