【问题标题】:Call a NSDictionary Value as Method调用 NSDictionary 值作为方法
【发布时间】:2012-12-03 04:09:44
【问题描述】:

我怎样才能调用一个函数,该函数的名称存储为一个 NSDictionary 的值?基本上我需要将字符串类型转换为方法名称/调用。这可能吗?

[thisCellContent objectForKey:@"callFunction"] //the object contains the function name to be called

//call this value as function, something similar to this ..
[self [thisCellContent objectForKey:@"callFunction"]]

这样的事情可能吗?

【问题讨论】:

  • 顺便说一下,这不是类型转换。

标签: objective-c


【解决方案1】:

不是这样,但你可以使用运行时/反射:

NSString *s = [thisCellContent objectForKey:@"callFunction"];
SEL sel = NSSelectorFromString(s);
[self performSelector:sel withObject:nil];

【讨论】:

  • Apple 文档说“performSelector: 方法相当于直接向接收者发送 aSelector 消息”。
【解决方案2】:

我建议将 Objective-C 块放入字典中。然后您可以调用该块(如果您愿意,它可以调用其他东西)。像这样的:

//In code that sets up the dictionary
void (^thingToCall)() = [^{ /* any code you want to run here */ } copy];
[dictionary setObject:thingToCall forKey:@"callFunction"];


//In code that uses the dictionary
void (^thingToCall)() = [dictionary objectForKey:@"callFunction"]; 
thingToCall(); //call the block

【讨论】:

  • 注意上面的block会被泄露。
  • 确实,我的 sn-ps 可能有点过于简短了。正常的 Cocoa 内存管理规则适用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 2010-11-07
相关资源
最近更新 更多