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
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);