NSInvocation与PerformSelector:方法的介绍与区别

NSInvocation与PerformSelector:的作用是一样的,都是可以直接调用某个对象的消息

异同点

相同点: 有相同的父类NSObject
区别: 在参数个数<= 2的时候performSelector:的使用要简单一些,但是在参数个数 > 2的时候NSInvocation就简单一些

使用

performSelector:的使用相对简单,主要用到以下几个方法

// 判断是否可以调用selector对应的方法
- (BOOL)canPerformAction:(SEL)action withSender:(nullable id)sender;
/* 直接调用的部分 */
// 当没有参数的时候调用的方法
- (id)performSelector:(SEL)aSelector;
// 当有一个参数的时候调用
- (id)performSelector:(SEL)aSelector withObject:(id)object;
// 当有两个参数的时候调用
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
/* 运用延迟的部分 */
// 普通延迟函数
- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;
//高级延迟函数
// 最后一个参数是RunLoopModes
- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray<NSString *> *)modes

举个例子:

if ([self canPerformAction:@selector(myLog:) withSender:nil]) {
    [self performSelector:@selector(myLog:) withObject:@"123" afterDelay:5];
}

- (void)myLog:(NSString*)log{
     NSLog(@"MyLog = %@",log);
  }

下面主要演示NSInvocation的使用

- (NSString*)textInvocation{
    // 函数初始化部分
    SEL selector = @selector(myLog:Log2:);
    NSMethodSignature *sig = [self methodSignatureForSelector:selector];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];

    // 设置参数
    invocation.target = self;
    invocation.selector = selector;

    NSString *log = @"我是log";
    NSString *log2 = @"我是log2";
    [invocation setArgument:&log atIndex:2];
    [invocation setArgument:&log2 atIndex:3];

    // 设置返回值
    NSString *result = nil;
    [invocation retainArguments];
    [invocation invoke];
    [invocation getReturnValue:&result];
    return result;
}

- (NSString*)myLog:(NSString*)log  Log2:(NSString*)log2{
     return [NSString stringWithFormat:@"MyLog==%@,Log2 == %@",log, log2];
}

其中的self可以替换成其他的类,然后相应的myLog:Log2需要替换成其他的类里面的方法

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 2,255评论 0赞 9
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 13,241评论 6赞 13
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,297评论 19赞 139
  • 传说中,有一种花,名为双生花。 一株并蒂,同生一木。 一株盛开在在深秋十月晚上月光最皎洁的时候,它们一蒂双花,亲密...
    安长挽阅读 569评论 10赞 9
  • 中服视觉出品 欢迎转载 请注明出处 橱窗就像行走在城市中的风景,给城市的白天黑夜,增加了无数的美好记忆。更是每位来...
    中服视觉阅读 920评论 0赞 0

友情链接更多精彩内容