OC:tableView的额外操作

背景:很多时候,我们需要对操作进行埋点。为了简便操作,可以尝试用下面的方式进行操作。

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:);
    
    //当delegate不能响应方法时, 直接返回
    if (![delegate respondsToSelector:originSEL]) {
        return;
    }
    
    //动态创建一个类
    Class originClass = object_getClass(delegate);
    NSString *originClassName = NSStringFromClass(originClass);
    
    //如果已经是动态创建的类了,就直接返回
    if ([originClassName hasPrefix:kClassPrefix]) {
        return;
    }
    
    NSString *subClassName = [kClassPrefix stringByAppendingString:originClassName];
    Class subClass = NSClassFromString(subClassName);
    if (!subClass) {
        //注册一个新类, 其父类为originClass
        subClass = objc_allocateClassPair(originClass, subClassName.UTF8String, 0);
        //获取当前类的方法指针
        Method currentMethod = class_getInstanceMethod(self, originSEL);
        IMP imp = method_getImplementation(currentMethod);
        const char *types = method_getTypeEncoding(currentMethod);
        //在subclass中添加对应的方法
        if (!class_addMethod(subClass, originSEL, imp, types)) {
            NSLog(@"方法: %@已经存在了", NSStringFromSelector(originSEL));
        }
        
        //获取当前类的 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(@"======已经有class存在了");
        }
    
        //注册新类
        objc_registerClassPair(subClass);
    }
    
    //修改isa指针的指向
    if (object_setClass(delegate, subClass)) {
        NSLog(@"成功将delegate的isa指向%@", subClass);
    }
}

- (Class)mz_class {
    // 获取对象的类
    Class class = object_getClass(self);
    // 将类名前缀替换成空字符串,获取原始类名
    NSString *className = [NSStringFromClass(class) stringByReplacingOccurrencesOfString:kClassPrefix withString:@""];
    // 通过字符串获取类,并返回
    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]);

    // 调用开发者自己实现的方法
    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);
    // 当原始方法不存在时,返回 NO,表示 Swizzling 失败
    if (!originalMethod) {
        return NO;
    }

    // 获取要交换的方法
    Method alternateMethod = class_getInstanceMethod(self, alternateSEL);
    // 当要交换的方法不存在时,返回 NO,表示 Swizzling 失败
    if (!alternateMethod) {
        return NO;
    }

    // 获取 originalSEL 方法的实现
    IMP originalIMP = method_getImplementation(originalMethod);
    // 获取 originalSEL 方法的类型
    const char * originalMethodType = method_getTypeEncoding(originalMethod);
    // 往类中添加 originalSEL 方法,如果已经存在会添加失败,并返回 NO
    if (class_addMethod(self, originalSEL, originalIMP, originalMethodType)) {
        // 如果添加成功了,重新获取 originalSEL 实例方法
        originalMethod = class_getInstanceMethod(self, originalSEL);
    }

    // 获取 alternateIMP 方法的实现
    IMP alternateIMP = method_getImplementation(alternateMethod);
    // 获取 alternateIMP 方法的类型
    const char * alternateMethodType = method_getTypeEncoding(alternateMethod);
    // 往类中添加 alternateIMP 方法,如果已经存在会添加失败,并返回 NO
    if (class_addMethod(self, alternateSEL, alternateIMP, alternateMethodType)) {
        // 如果添加成功了,重新获取 alternateIMP 实例方法
        alternateMethod = class_getInstanceMethod(self, alternateSEL);
    }

    // 交换两个方法的实现
    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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,539评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,594评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,871评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,963评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,984评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,763评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,468评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,850评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,002评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,144评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,823评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,483评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,026评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,150评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,415评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,092评论 2 355

推荐阅读更多精彩内容