runtime-class_addMethod\objc_msgSend\NSInvocation

本文介绍如何使用Objective-C运行时API动态地为类添加方法,并通过两种方式调用这些方法:直接发送消息和使用NSInvocation。文章还提供了一个具体的例子来展示整个过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#import <objc/runtime.h>

#import <objc/message.h>


  TestClass *instance = [[TestClass alloc]init];
    //给testclass添加一个fun
    class_addMethod([TestClass class],@selector(ocMethodA::), (IMP)cfunctionA,"@@:@@");
    
    
    
    if ([instance respondsToSelector:@selector(ocMethodA::)]) {
        
        NSLog(@"Yes, instance respondsToSelector:@selector(ocMethodA::)");
        NSString *myString = @"我是一个OC的method,C函数实现";
        NSString *myString2 = @"-----我是第二个参数";
        
        
        //方法1
        objc_msgSend(instance, @selector(ocMethodA::),myString,myString2);
        
        
        //方法2
        SEL mySelector = @selector(ocMethodA::);
        NSMethodSignature * sig = [[TestClass class]  instanceMethodSignatureForSelector: mySelector];
        NSInvocation * myInvocation = [NSInvocation invocationWithMethodSignature: sig];
        [myInvocation setTarget: instance];//0
        [myInvocation setSelector: mySelector];//1
        [myInvocation setArgument: &myString atIndex: 2];
        [myInvocation setArgument: &myString2 atIndex: 3];
        NSString* result = nil;
        [myInvocation retainArguments];
        [myInvocation invoke];
        [myInvocation getReturnValue: &result];
        NSLog(@"The NSInvocation invoke string is: %@", result);
        
    }
    else
    {
        
        NSLog(@"Sorry");
        
    }

NSString* cfunctionA(id self, SEL _cmd, NSString *str, NSString *str1) {
    
    NSLog(@"%@%@", str,str1);
    
    return @"结果返回";//随便返回个值
    
}



 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值