iphone - 如何使用 NSString 或 const char *name 动态调用 Objective-C 中的方法?

标签 iphone objective-c ios

我正在使用 Objective-C 中的动态编程进行一些工作,并且我已经通读了 Objective-C Runtime Programming Guide 并能够完成我需要的大部分工作,但是我没有做的一件事我想出了如何动态调用一个方法,前提是我有它的字符串表示形式。

本质上,我动态地查找属性以查看我的对象是否具有与使用 class_copyPropertyList 的列表匹配的属性,然后循环遍历并通过从 plist 文件填充的 NSMutableDictionary 匹配这些属性。找到匹配项后,我想执行该属性。我无法提前知道可能存在哪些匹配项,因为这是一个将打包到许多不同应用程序中的库。

最佳答案

使用 NSSelectorFromStringNSString 创建一个 SEL。然后您可以使用 performSelector 方法之一执行它。

动态设置属性:

SEL setter = NSSelectorFromString(@"setProperty:");
[myObject performSelector:setter withObject:newValue];

动态获取属性:

SEL getter = NSSelectorFromString(@"property");
id myProperty = [myObject performSelector:getter];

对于更复杂的方法,您可以使用 NSInvocationNSMethodSignature :

SEL action = NSSelectorFromString(@"someMethod:withArguments:");
NSMethodSignature *signature = [myObject methodSignatureForSelector:action];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setArgument:arg1 atIndex:2]; // indices 0 and 1 are reserved.
[invocation setArgument:arg2 atIndex:3];
[invocation invokeWithTarget:myObject];
id returnedObject;
[invocation1 getReturnValue:&returnedObject];

关于iphone - 如何使用 NSString 或 const char *name 动态调用 Objective-C 中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13441531/

相关文章:

ios - 如何创建 "Secret"之类的表格 View 动画?

ios - 磁盘上的 PFFile 位置

javascript - 变量似乎没有在移动设备上设置

iphone - 在另一个 View 的 UIImageView 上设置图像

iphone - 我们应该手动释放 NSDate 吗?

iphone - 使用quartz-2d时如何实现触摸

ios - 如何在iOS中实现Google和Facebook网址处理?

ios - 如何从单元格调用父 TableView 方法?

ios - 应用程序在 iOS6 中运行良好,在 iOS7 中运行缓慢且不稳定

iphone - 为什么我的 CGContext 绘制的圆很糟糕?