背景:很多時(shí)候,我們需要對(duì)操作進(jìn)行埋點(diǎn)。為了簡(jiǎn)便操作,可以嘗試用下面的方式進(jìn)行操作。
UIScrollView (MZDatas)
//.h
#import <UIKit/UIKit.h>
#import "MZSubScrollViewDelegateProxy.h"
NS_ASSUME_NONNULL_BEGIN
@interface UIScrollView (MZDatas)
@property (nonatomic, strong, nullable) MZSubScrollViewDelegateProxy *delegateProxy;
@end
NS_ASSUME_NONNULL_END
//.m
#import "UIScrollView+MZDatas.h"
#include <objc/runtime.h>
@implementation UIScrollView (MZDatas)
- (void)setDelegateProxy:(MZSubScrollViewDelegateProxy *)delegateProxy {
objc_setAssociatedObject(self, @selector(delegateProxy), delegateProxy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (MZSubScrollViewDelegateProxy *)delegateProxy {
return objc_getAssociatedObject(self, _cmd);
}
@end
UITableView (MZDatas)
//.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UITableView (MZDatas)
@end
NS_ASSUME_NONNULL_END
//.m
#import "UITableView+MZDatas.h"
#import "NSObject+MZDatas.h"
#import "MZSubScrollViewDelegateProxy.h"
#import "MZSubScrollViewDynamicDelegate.h"
#import "UIScrollView+MZDatas.h"
@implementation UITableView (MZDatas)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[UITableView mz_swizzleOriginSel:@selector(setDelegate:) withAlternateSel:@selector(mz_setDelegate:)];
});
}
- (void)mz_setDelegate:(id<UITableViewDelegate>)delegate {
[self mz_setDelegate:delegate];
[MZSubScrollViewDynamicDelegate proxyWithTableViewDelegate:delegate];
// 方法二
// self.delegateProxy = nil;
// if (delegate) {
// MZSubScrollViewDelegateProxy *proxy = [MZSubScrollViewDelegateProxy proxyWithTableViewDelegate:delegate];
// self.delegateProxy = proxy;
// [self mz_setDelegate:proxy];
// } else {
// [self mz_setDelegate:nil];
// }
}
@end
MZSubScrollViewDelegateProxy
//.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface MZSubScrollViewDelegateProxy : NSProxy<UITableViewDelegate, UICollectionViewDelegate>
+ (instancetype)proxyWithTableViewDelegate:(id<UITableViewDelegate>)delegate;
+ (instancetype)proxyWithCollectionViewDelegate:(id<UICollectionViewDelegate>)delegate;
@end
NS_ASSUME_NONNULL_END
//.m
#import "MZSubScrollViewDelegateProxy.h"
@interface MZSubScrollViewDelegateProxy ()
@property (nonatomic, weak) id delegate;
@end
@implementation MZSubScrollViewDelegateProxy
+ (instancetype)proxyWithTableViewDelegate:(id<UITableViewDelegate>)delegate {
MZSubScrollViewDelegateProxy *proxy = [MZSubScrollViewDelegateProxy alloc];
proxy.delegate = delegate;
return proxy;
}
+ (instancetype)proxyWithCollectionViewDelegate:(id<UICollectionViewDelegate>)delegate {
MZSubScrollViewDelegateProxy *proxy = [MZSubScrollViewDelegateProxy alloc];
proxy.delegate = delegate;
return proxy;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
return [self.delegate methodSignatureForSelector:sel];
}
- (void)forwardInvocation:(NSInvocation *)invocation {
[invocation invokeWithTarget:self.delegate];
if (invocation.selector == @selector(tableView:didSelectRowAtIndexPath:)) {
invocation.selector = @selector(mz_tableView:didSelectRowAtIndexPath:);
[invocation invokeWithTarget:self];
} else if (invocation.selector == @selector(collectionView:didSelectItemAtIndexPath:)) {
invocation.selector = @selector(mz_collectionView:didSelectItemAtIndexPath:);
[invocation invokeWithTarget:self];
}
}
- (void)mz_tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"%s", __func__);
}
- (void)mz_collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"%s", __func__);
}
@end
MZSubScrollViewDynamicDelegate
//.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface MZSubScrollViewDynamicDelegate : NSObject
+ (void)proxyWithTableViewDelegate:(id<UITableViewDelegate>)delegate;
@end
NS_ASSUME_NONNULL_END
//.m
#import "MZSubScrollViewDynamicDelegate.h"
#import <objc/runtime.h>
static NSString *const kClassPrefix = @"com.bat.lynn.";
typedef void (*MZImplementation)(id, SEL, UITableView *, NSIndexPath *);
@implementation MZSubScrollViewDynamicDelegate
+ (void)proxyWithTableViewDelegate:(id<UITableViewDelegate>)delegate {
SEL originSEL = @selector(tableView:didSelectRowAtIndexPath:);
//當(dāng)delegate不能響應(yīng)方法時(shí), 直接返回
if (![delegate respondsToSelector:originSEL]) {
return;
}
//動(dòng)態(tài)創(chuàng)建一個(gè)類
Class originClass = object_getClass(delegate);
NSString *originClassName = NSStringFromClass(originClass);
//如果已經(jīng)是動(dòng)態(tài)創(chuàng)建的類了,就直接返回
if ([originClassName hasPrefix:kClassPrefix]) {
return;
}
NSString *subClassName = [kClassPrefix stringByAppendingString:originClassName];
Class subClass = NSClassFromString(subClassName);
if (!subClass) {
//注冊(cè)一個(gè)新類, 其父類為originClass
subClass = objc_allocateClassPair(originClass, subClassName.UTF8String, 0);
//獲取當(dāng)前類的方法指針
Method currentMethod = class_getInstanceMethod(self, originSEL);
IMP imp = method_getImplementation(currentMethod);
const char *types = method_getTypeEncoding(currentMethod);
//在subclass中添加對(duì)應(yīng)的方法
if (!class_addMethod(subClass, originSEL, imp, types)) {
NSLog(@"方法: %@已經(jīng)存在了", NSStringFromSelector(originSEL));
}
//獲取當(dāng)前類的 mz_class 方法指針
Method classMethod = class_getInstanceMethod(self, @selector(mz_class));
IMP clsImp = method_getImplementation(classMethod);
const char *clsTypes = method_getTypeEncoding(classMethod);
//在subclass中添加 class 方法
if (!class_addMethod(subClass, @selector(class), clsImp, clsTypes)) {
NSLog(@"======已經(jīng)有class存在了");
}
//注冊(cè)新類
objc_registerClassPair(subClass);
}
//修改isa指針的指向
if (object_setClass(delegate, subClass)) {
NSLog(@"成功將delegate的isa指向%@", subClass);
}
}
- (Class)mz_class {
// 獲取對(duì)象的類
Class class = object_getClass(self);
// 將類名前綴替換成空字符串,獲取原始類名
NSString *className = [NSStringFromClass(class) stringByReplacingOccurrencesOfString:kClassPrefix withString:@""];
// 通過(guò)字符串獲取類,并返回
return objc_getClass([className UTF8String]);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// 獲取原始類
Class cla = object_getClass(tableView.delegate);
NSString *className = [NSStringFromClass(cla) stringByReplacingOccurrencesOfString:kClassPrefix withString:@""];
Class originalClass = objc_getClass([className UTF8String]);
// 調(diào)用開(kāi)發(fā)者自己實(shí)現(xiàn)的方法
SEL originalSelector = NSSelectorFromString(@"tableView:didSelectRowAtIndexPath:");
Method originalMethod = class_getInstanceMethod(originalClass, originalSelector);
IMP originalImplementation = method_getImplementation(originalMethod);
if (originalImplementation) {
((MZImplementation)originalImplementation)(tableView.delegate, originalSelector, tableView, indexPath);
}
NSLog(@"class: %@, %s", self.class, __func__);
}
@end
UICollectionView (MZDatas)
//.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UICollectionView (MZDatas)
@end
NS_ASSUME_NONNULL_END
//.m
#import "UICollectionView+MZDatas.h"
#import "NSObject+MZDatas.h"
#import "MZSubScrollViewDelegateProxy.h"
#import "UIScrollView+MZDatas.h"
@implementation UICollectionView (MZDatas)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[UICollectionView mz_swizzleOriginSel:@selector(setDelegate:) withAlternateSel:@selector(mz_setDelegate:)];
});
}
- (void)mz_setDelegate:(id<UITableViewDelegate>)delegate {
self.delegateProxy = nil;
if (delegate) {
MZSubScrollViewDelegateProxy *proxy = [MZSubScrollViewDelegateProxy proxyWithTableViewDelegate:delegate];
self.delegateProxy = proxy;
[self mz_setDelegate:proxy];
} else {
[self mz_setDelegate:nil];
}
}
@end
NSObject (MZDatas)
//.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSObject (MZDatas)
+ (BOOL)mz_swizzleOriginSel:(SEL)originalSEL withAlternateSel:(SEL)alternateSEL;
@end
NS_ASSUME_NONNULL_END
//.m
#import "NSObject+MZDatas.h"
#import <objc/runtime.h>
@implementation NSObject (MZDatas)
+ (BOOL)mz_swizzleOriginSel:(SEL)originalSEL withAlternateSel:(SEL)alternateSEL {
// 獲取原始方法
Method originalMethod = class_getInstanceMethod(self, originalSEL);
// 當(dāng)原始方法不存在時(shí),返回 NO,表示 Swizzling 失敗
if (!originalMethod) {
return NO;
}
// 獲取要交換的方法
Method alternateMethod = class_getInstanceMethod(self, alternateSEL);
// 當(dāng)要交換的方法不存在時(shí),返回 NO,表示 Swizzling 失敗
if (!alternateMethod) {
return NO;
}
// 獲取 originalSEL 方法的實(shí)現(xiàn)
IMP originalIMP = method_getImplementation(originalMethod);
// 獲取 originalSEL 方法的類型
const char * originalMethodType = method_getTypeEncoding(originalMethod);
// 往類中添加 originalSEL 方法,如果已經(jīng)存在會(huì)添加失敗,并返回 NO
if (class_addMethod(self, originalSEL, originalIMP, originalMethodType)) {
// 如果添加成功了,重新獲取 originalSEL 實(shí)例方法
originalMethod = class_getInstanceMethod(self, originalSEL);
}
// 獲取 alternateIMP 方法的實(shí)現(xiàn)
IMP alternateIMP = method_getImplementation(alternateMethod);
// 獲取 alternateIMP 方法的類型
const char * alternateMethodType = method_getTypeEncoding(alternateMethod);
// 往類中添加 alternateIMP 方法,如果已經(jīng)存在會(huì)添加失敗,并返回 NO
if (class_addMethod(self, alternateSEL, alternateIMP, alternateMethodType)) {
// 如果添加成功了,重新獲取 alternateIMP 實(shí)例方法
alternateMethod = class_getInstanceMethod(self, alternateSEL);
}
// 交換兩個(gè)方法的實(shí)現(xiàn)
method_exchangeImplementations(originalMethod, alternateMethod);
// 返回 YES,表示 Swizzling 成功
return YES;
}
@end
使用
#import "TableViewController.h"
@implementation TableViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TablViewCellID" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"朕親自扇了你一巴掌: %ld", indexPath.row);
UITableViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"TableViewController"];
[self.navigationController pushViewController:vc animated:YES];
}
@end