杂记
交换方法
+ (void)exchangeInstanceMethod:(Class)anClass method1Sel:(SEL)method1Sel method2Sel:(SEL)method2Sel {
Method originalMethod = class_getInstanceMethod(anClass, method1Sel);
Method swizzledMethod = class_getInstanceMethod(anClass, method2Sel);
BOOL didAddMethod =
class_addMethod(anClass,
method1Sel,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(anClass,
method2Sel,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
}
else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
BOOL didAddMethod =
class_addMethod(anClass,
method1Sel,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
给类添加方法1的方法名方法2的方法实现和参数,如果返回成功,那就说明类不存在方法1,直接给类添加了新方法名为方法1方法实现为方法2的方法,然后将类中方法名为方法2的方法的实现替换为方法1的实现;如果返回为NO,证明类中存在方法名为方法1的方法,下面进行交换
响应者链逆向传值
响应者链是从UIApplication->UIViewController->UIView->TableView->cell
cell是第一响应者,所谓的逆向就是从第一响应者到第二响应者或者第三响应者的传值。对层view层较多的情况非常有效。
- 给添加UIResponder添加分类
- 添加方法 - (void)userInterfaceAction:(NSString *)eventName userInfo:(NSDictionary *)userInfo
- 实现方法
- (void)userInterfaceAction:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
if (self.nextResponder) {
[self.nextResponder userInterfaceAction:eventName userInfo:userInfo];
}
}
在需要调用的地方直接调用分类方法,根据eventName参数进行区分(比如在cell中),在需要拦截的地方也实现方法,在方法中进行处理。(比如UIViewController中)。