runtime 方法替换实现

这篇博客介绍了如何使用Objective-C的runtime来实现方法的替换。通过`swizzle`函数,将`ViewController`类中的`method1`方法替换为`method2`,并展示了替换后的调用过程。博客内容涉及`class_getInstanceMethod`、`method_exchangeImplementations`等runtime方法的应用。
摘要由CSDN通过智能技术生成

   

//    _imageURL = [imageURLS retain];

    

    _request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://avatar.csdn.net/2/C/D/1_totogo2010.jpg"]];

    _conn    = [[NSURLConnection alloc] initWithRequest:_request delegate:self];

    

    _incrementallyimgSource = CGImageSourceCreateIncremental(NULL);

    

    _recieveData = [[NSMutableData alloc] init];

    _isLoadFinished = false;



    view = [[UIImageView alloc] initWithFrame:CGRectMake(10,10, 300, 300)];

    

    view.image = self.image;

    

   

    SEL ors = @selector(method1);

    SEL news = @selector(method2);

    Class c = NSClassFromString(@"ViewController");

    

    BOOL succesed = swizzle(c,ors,news);

     [self method2];

    NSLog(@"succesed  :%d",succesed);

}


BOOL swizzle(Class c,SEL origSelector, SEL newSelector)

{

    Method origMethod = class_getInstanceMethod(c, origSelector);

    Method newMethod = class_getInstanceMethod(c, newSelector);

    

    if (origMethod && newMethod) {

        if (class_addMethod(c, origSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {

            class_replaceMethod(c, newSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));

        } else {

            method_exchangeImplementations(origMethod, newMethod);

        }

        return YES;

    }

    return NO;

}




- (void)method1{

 [self.view addSubview:view];

    NSLog(@"         method1 ");

}


- (void)method2{


    NSLog(@"         method2 ");

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值