iOS資料埋點統計方案(附Demo): 執行時Method Swizzling機制與AOP程式設計(面向切面程式設計)...
阿新 • • 發佈:2019-02-04
@implementation UIViewController (Trace)
+ (void)load{
swizzleMethod([self class], @selector(viewDidAppear:), @selector(swizzled_viewDidAppear:));
}
- (void
// call original implementation
[self swizzled_viewDidAppear:animated];
// Begin statistics Event
[TraceHandler statisticsWithEventName:@"UIViewController"];
}
void swizzleMethod(Class class,SEL originalSelector,SEL swizzledSelector){
// the method might not exist in the class, but in its superclass
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
// class_addMethod will fail if original method already exists
BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
// the method doesn’t exist and we just added one
if (didAddMethod) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}
else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
@end
TraceHandler.m
@implementation TraceHandler
+ (void)statisticsWithEventName:(NSString *)eventName{
NSLog(@"-----> %@",eventName);
}
@end