Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 在Objective C中从另一个类动态调用方法_Objective C_Objective C Category - Fatal编程技术网

Objective c 在Objective C中从另一个类动态调用方法

Objective c 在Objective C中从另一个类动态调用方法,objective-c,objective-c-category,Objective C,Objective C Category,我试图从另一个源文件中的另一个类调用一个方法 例如: 我有一个文件名为Source1.h/Source1.m(都是目标C类文件) 我还有另一个文件名Source2.h/Source2.m(都是目标C类文件) Source1包含两种方法,例如:method1和method2 从Source2文件,我需要从source1文件调用method1 我知道如何在objective C中实现这一点。但是在我的source2文件中,Source1中的方法名称将被动态检索。我不会硬编码类似的东西 Source1

我试图从另一个源文件中的另一个类调用一个方法

例如:

  • 我有一个文件名为
    Source1.h/Source1.m
    (都是目标C类文件)
  • 我还有另一个文件名
    Source2.h/Source2.m
    (都是目标C类文件)
  • Source1
    包含两种方法,例如:
    method1
    method2
  • Source2
    文件,我需要从
    source1
    文件调用
    method1
  • 我知道如何在objective C中实现这一点。但是在我的
    source2
    文件中,
    Source1
    中的方法名称将被动态检索。我不会硬编码类似的东西

    Source1 *a = [[Source1 alloc]init];
    
    [a method1];
    
    method1
    文本将取自文本文件。我可以使用选择器从同一个类调用方法。但我不能使用选择器从另一个类调用方法

    请帮助解决这个问题


    非常感谢……

    这个答案似乎与此相关:


    基本上,您可以使用NSSELECTOR FROMSTRING从NSString中的UTF8字符串创建选择器。

    您可以这样做:

    MyClass包含名为
    myMethod
    的方法,该方法是从其他类调用的

    MyClass *object=[MyClass new];
    
    SEL mySelector=NSSelectorFromString(@"myMethod"); //myMethod is a string, that you can read from any text file/source file and use it here.
    
    //以下内容将在ARC中创建警告,您可以通过添加这些内容来抑制警告

    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [object performSelector:mySelector];
    #pragma clang diagnostic pop
    
    另一种方法是这样做:

    #import <objc/message.h>//This is required to import
    
    MyClass *object=[MyClass new]; 
    SEL mySelector=NSSelectorFromString(@"myMethod");
    objc_msgSend(object,mySelector);