1. 程式人生 > >iOS資料埋點統計方案(附Demo): 執行時Method Swizzling機制與AOP程式設計(面向切面程式設計)...

iOS資料埋點統計方案(附Demo): 執行時Method Swizzling機制與AOP程式設計(面向切面程式設計)...

#import "UIViewController+Trace.h"
#import "TraceHandler.h"
#import <objc/runtime.h>
#import <objc/objc.h>
#import "Aspects.h"
@implementation UIViewController (Trace)
#pragma mark - 1.自定義實現方法
+ (void)load{
   swizzleMethod([self class], @selector(viewDidAppear:), @selector(swizzled_viewDidAppear:));
}
- (void
)swizzled_viewDidAppear:(BOOL)animated{
   // 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
#import "TraceHandler.h"
@implementation TraceHandler
+ (void)statisticsWithEventName:(NSString *)eventName{
   NSLog(@"-----> %@",eventName);
}
@end