iOS NSInvocation

苹果文档:

An NSInvocation is an Objective-C message rendered static, that is, it is an action turned into an object. NSInvocation objects are used to store and forward messages between objects and between applications, primarily by NSTimer objects and the distributed objects system. 

An NSInvocation object contains all the elements of an Objective-C message: a target, a selector, arguments, and the return value. Each of these elements can be set directly, and the return value is set automatically when the NSInvocation object is dispatched.

An NSInvocation object can be repeatedly dispatched to different targets; its arguments can be modified between dispatch for varying results; even its selector can be changed to another with the same method signature (argument and return types). This flexibility makes NSInvocation useful for repeating messages with many arguments and variations; rather than retyping a slightly different expression for each message, you modify the NSInvocation object as needed each time before dispatching it to a new target.

NSInvocation does not support invocations of methods with either variable numbers of arguments or unionarguments. You should use the invocationWithMethodSignature: class method to create NSInvocationobjects; you should not create these objects using alloc and init.

This class does not retain the arguments for the contained invocation by default. If those objects might disappear between the time you create your instance of NSInvocation and the time you use it, you should explicitly retain the objects yourself or invoke the retainArguments method to have the invocation object retain them itself.

Getting the Method Signature

   Creating NSInvocation Objects

Dispatching an Invocation

  •    - invokeWithTarget:

    简单例子:
    - ( void )viewDidLoad {
         [super viewDidLoad];
         SEL myMethod = @selector(myLog);
         //创建一个函数签名,这个签名可以是任意的,但需要注意,签名函数的参数数量要和调用的一致。
         NSMethodSignature * sig  = [NSNumber instanceMethodSignatureForSelector:@selector(init)];
         //通过签名初始化 不能用init/alloc
         NSInvocation * invocatin = [NSInvocation invocationWithMethodSignature:sig];
         //设置target
         [invocatin setTarget:self];
         //设置selecteor
         [invocatin setSelector:myMethod];
         //消息调用
         [invocatin invoke];
         
    }
    -( void )myLog{
         NSLog(@ "MyLog" );
    }



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值