• 关于 NSInvocation


    Invocation   调用的意思。

    可想而知NSInvocation 是一个 方法调用 封装的类。

    这体现了  面向对象的思想, 及一切皆对象。函数也不例外。

    一般编程中,应该很少用到这个。 但是要编写 抽象度高的 框架,或 代码。 这个是必不可少的。

    跟 c# , java 里的 反射 类似 。 动态访问 和 调用方法。

    下面介绍下简单使用。。

    用之前可以先 自己想下。如果让你 来 封装一个函数 作为一个类 ,都需要什么。

    funObj  函数 对象

    funObj 属性 

    funObj 行为(方法fun)

    首先属性,需要 函数的一个描述:

    {

     1,唯一标示 一个函数

     2,函数 在 程序里的 调用指针。

    }

    函数的参数:

    {

    arg 1

    arg 2

    }

    函数的返回值:

    {

    returnValue

    }

    函数的调用对象

    {

    要调用方法的外部对象。

    }

    其次   函数对象的行为(fun)

    {

    有了足够多的信息后,我们就可以 拿到 外部调用对象 去 内存里找 函数的调用地址, 加上函数参数、返回值。 来调用函数。

    }

    以上这些,在面向对象的语言里 可能已经为我们封装了,OC 中的NSInvocation 就是。

    对于调用一个 有两个参数以上的   函数,我们可以这样:

    -( id )fun :(id) a :(id)b ......{

    }

    [self    fun:a : b .....]; //很简单啊。这是在确定的情况下。不确定呢,

    使用

    [self performSelector:@selector() withObject: .....];

    很遗憾 只能传递一个参数, 除非你把 a,b 参数放倒一个 集合中。

    使用NSInvocation
    -(NSString *)customMethod:(NSString *)arg1 otherArg:(NSString *)arg2{
        
        return [NSString stringWithFormat:@"%@%@",arg1,arg2];
        
    }
    
    
        SEL customSel = @selector(customMethod: otherArg:);
        
        NSMethodSignature * customSig = [self methodSignatureForSelector:customSel];
        
        NSInvocation *customInvocation =  [NSInvocation  invocationWithMethodSignature:customSig ];
        NSString *arg1 = @"NS";
        NSString *arg2 = @"Invocation";
    
        [customInvocation setTarget:self];
        [customInvocation setReturnValue:@encode(NSString)];
        
        [customInvocation setSelector:customSel];
        [customInvocation setArgument:&arg1 atIndex:2];
        [customInvocation setArgument:&arg2 atIndex:3];
    
        [customInvocation invoke];

        SEL customSel = @selector(customMethod: otherArg:); 

     
  • 相关阅读:
    分享两个你可能不知道的Java小秘密
    一次ssl的手动实现——加密算法的简单扫荡
    TCP/IP中最高大上的链路层简介(二)
    与TCP/IP协议的初次见面(一)
    高并发下的九死一生,一个不小心就掉入万丈深渊
    杂谈---一个项目经理的自我反省
    浅谈程序员的行业选择---程序人生
    杂谈---大压力下的工作
    一个有意思的需求——中文匹配度
    杂谈---一个人的两种心理
  • 原文地址:https://www.cnblogs.com/DamonTang/p/4034993.html
Copyright © 2020-2023  润新知