KVC:使用字符串来描述对象需要更改的属性,用来获取或修改对象的属性值。
[Student setValue:@"1234" forKeyPath: @"card.no"];
[Student valueForKeyPath:@"card.no"]
KVO是一种非常重要的机制,用来监听对象属性的变化。
//1.添加观察者
[stu addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
//2.实现监听方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if([keyPath isEqualToString:@"frame"]) {
NSLog(@"keyPath=%@,object=%@,newValue=%.2f,context=%@",keyPath,object,[[change objectForKey:@"new"] floatValue],context);
}
}
//3.移除监听器
[stu removeObserver:self forKeyPath:@"frame"];
然后用Swift举个例子:监听当前控制器frame的变化修改按钮的frame
init() {
super.init(frame: CGRect.init(x: 0, y: ScreenHeight - 49, width: ScreenWidth, height: 49))
self.addSubview(plusButton)
//KVC赋值
plusButton .setValue(CGPoint.init(x: ScreenWidth / 2, y: 49 - plusButton.bounds.size.height / 2), forKey: "center")
//添加KVO
self .addObserver(self, forKeyPath: "frame", options: .new, context: nil)
}
convenience init(delegate: LAXTabBarDelegate) {
self.init()
self.tabbarDelegate = delegate
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
//移除KVO
removeObserver(self, forKeyPath: "frame")
}
//实现KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "frame" {
if let rect = change?[.newKey] as? CGRect {
plusButton .setValue(CGPoint.init(x: rect.size.width / 2, y: 49 - plusButton.bounds.size.height / 2), forKey: "center")
}
}
}