MyObject+Tracking.h如下
//
// MyObjct+Tracking.h
// Test10
//
// Created by lagou on 15/12/2.
// Copyright © 2015年 lagou. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "MyObject.h"
@interface MyObject(Tracking)
@end
MyObject+Tracking.m如下
#import "MyObjct+Tracking.h"
#import <objc/runtime.h>
@implementation MyObject (Tracking)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class aClass = [self class];
SEL originaSelector = @selector(testData);//初始方法
SEL swizzSelector = @selector(xxx_testData);//替换方法
Method originaMethod = class_getInstanceMethod(aClass, originaSelector);
Method swizzMethod = class_getInstanceMethod(aClass, swizzSelector);
BOOL didAddMethod = class_addMethod(aClass, swizzSelector, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
if (didAddMethod) {
NSLog(@"1");
class_replaceMethod(aClass, @selector(xxx_testData), method_getImplementation(originaMethod), method_getTypeEncoding(originaMethod));
} else {
NSLog(@"2");
method_exchangeImplementations(originaMethod, swizzMethod);
}
});
}
- (void)xxx_testData {
[self xxx_testData];//调用的是testData,不是xxx_testData
NSLog(@"xxxx-testData:%@", self);
}
@end
子类重写时必须调用父类的方法,否则不会拦截!!!!!!
#import "SecondObject.h"
@implementation SecondObject
- (void)testData {
[super testData];
NSLog(@"second--data");
}
@end
1.结果:[self testData]调用的是xxx_testData;
[self xxx_testData]调用的是testData;
2.load方法是在程序启动时加载的,即便不引用Myoject.h头文件