1. KVC
KVC
(key-value-coding)键值编码,是一种间接访问实例变量的方法。提供一种机制来间接访问对象的属性。
1、给私有变量赋值。
2、给控件的内部属性赋值。
// 自定义UITextFiled的placeholder的颜色,一般可利用runtime获取控件的内部属性名,
// Ivar *ivar = class_getInstanceVariable获取实例成员变量
[textField setValue:[UIColor redColor] forKeyPath:@"placeholderLabel.textColor"];
3、结合Runtime,model和字典的转换
(setValuesForKeysWithDictionary,class_copyIvarList获取指定类的Ivar成员列表)
2. 图解KVO
KVO是一种基于KVC实现的观察者模式。当指定的被观察的对象的属性更改了,KVO会以自动或手动方式通知观察者。
3. Swizzle the methods.
+ (void)swizzleSelector:(SEL)originalSelector inClass:(Class)originalClass withSelector:(SEL)swizzledSelector inClass:(Class)swizzledClass {
Method originalMethod = class_getInstanceMethod(originalClass, originalSelector);
Method swizzledMethod = class_getInstanceMethod(swizzledClass, swizzledSelector);
BOOL didAddMethod =
class_addMethod(originalClass,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(originalClass,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}