美文网首页
ios 交换方法

ios 交换方法

作者: _蓝星 | 来源:发表于2022-01-10 21:19 被阅读0次

    1.类/分类添加方法后交换

    [[Person alloc] eat];
    [[Person alloc] swizzleEat];
    [[Person alloc] eat];
    
    - (void)eat {
        NSLog(@"吃蔬菜");
    }
    
    - (void)swizzle_eat {
        NSLog(@"吃水果");
    }
    
    - (void)swizzleEat {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            Method eatMethod = class_getInstanceMethod([self class], @selector(eat));
            Method swizzleEatMethod = class_getInstanceMethod([self class], @selector(swizzle_eat));
            BOOL addSucceed = class_addMethod([self class], @selector(swizzle_eat), method_getImplementation(swizzleEatMethod), method_getTypeEncoding(eatMethod));
            if (addSucceed) {
                class_replaceMethod([self class], @selector(swizzle_eat), method_getImplementation(eatMethod), method_getTypeEncoding(eatMethod));
            }else {
                method_exchangeImplementations(eatMethod, swizzleEatMethod);
            }
        });
    }
    

    结果:

    2022-01-10 21:19:15.211439+0800 TestDemo[27126:498987] 吃蔬菜
    2022-01-10 21:19:15.211748+0800 TestDemo[27126:498987] 吃水果
    

    2.创建并交换实例方法

    [[Person alloc] eat];
    
    Class class = [Person class];
    SEL selector = @selector(eat);
    SEL swizzledSelector = NSSelectorFromString(@"eat_meet");
    Method originEat = class_getInstanceMethod(class, selector);
    void (^swizzleBlock)(void) = ^(void) {
         NSLog(@"吃火锅");
    };
    IMP swizzleIMP = imp_implementationWithBlock(swizzleBlock);
    class_addMethod(class, swizzledSelector, swizzleIMP, method_getTypeEncoding(originEat));
    Method swizzleMethod = class_getInstanceMethod(class, swizzledSelector);
    method_exchangeImplementations(originEat, swizzleMethod); 
    [[Person alloc] eat];
    

    结果:

    2022-01-10 21:18:02.564029+0800 TestDemo[27076:497657] 吃蔬菜
    2022-01-10 21:18:02.564333+0800 TestDemo[27076:497657] 吃火锅
    

    3.创建并交换类方法

    + (void)run {
        NSLog(@"慢步");
    }
    
    [Person run];
    SEL runSelector = @selector(run);
    SEL runSwizzledSelector = NSSelectorFromString(@"run_quick");
    Method runOrigin = class_getClassMethod(class, runSelector);
    void (^runSwizzleBlock)(void) = ^(void) {
       NSLog(@"快跑");
    };
    IMP runSwizzleIMP = imp_implementationWithBlock(runSwizzleBlock);
    class_addMethod(object_getClass([Person class]), runSwizzledSelector, runSwizzleIMP, method_getTypeEncoding(runOrigin));
    Method runSwizzleMethod = class_getClassMethod(class, runSwizzledSelector);
    method_exchangeImplementations(runOrigin, runSwizzleMethod);    [Person run];
    

    结果:

    2022-01-10 21:18:02.564458+0800 TestDemo[27076:497657] 慢步
    2022-01-10 21:18:02.564662+0800 TestDemo[27076:497657] 快跑
    

    相关文章

      网友评论

          本文标题:ios 交换方法

          本文链接:https://www.haomeiwen.com/subject/tzqvcrtx.html