首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

NSInvocation运用示例

2012-12-23 
NSInvocation使用示例一、概述在 iOS中可以直接调用 某个对象的消息 方式有2种第一种方式是使用NSObject类

NSInvocation使用示例
一、概述

在 iOS中可以直接调用 某个对象的消息 方式有2种


第一种方式是使用NSObject类提供的performSelector系列方法


还有一种方式就是使用NSInvocation进行动态运行时的消息分发,动态的执行方法,相信大家一定经常使用NSObject类提供的performSelector系列方法,在这里就不再对此进行描述了,今天主要是分享一下使用NSInvocation动态执行方法。


二、NSInvocation的使用1、执行类方法

demo代码如下:

- (void)testInstanceMethod{    NSString *string = [NSString stringWithFormat:@"我是一个string"];    NSLog(@"1=%@",string);    SEL subStringSel = @selector(substringFromIndex:);        //初始化NSMethodSignature对象    NSMethodSignature *methodSignature = [[NSString class] instanceMethodSignatureForSelector:subStringSel];        //初始化NSInvocation对象    NSInvocation *myInvocation = [NSInvocation invocationWithMethodSignature:methodSignature];        //设置target    [myInvocation setTarget:string];        //设置selector    [myInvocation setSelector:subStringSel];        //设置参数    int arg1 =  2;    [myInvocation setArgument:&arg1 atIndex:2];//参数从2开始,index 为0表示target,1为_cmd        //获取结果    NSString *resultString = nil;    [myInvocation invoke];    [myInvocation getReturnValue:&resultString];    NSLog(@"2=%@",resultString);}


热点排行