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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容