2

我怎样才能调用一个函数,该函数的名称存储为一个 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"]]

这样的事情可能吗?

4

2 回答 2

4

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

NSString *s = [thisCellContent objectForKey:@"callFunction"];
SEL sel = NSSelectorFromString(s);
[self performSelector:sel withObject:nil];
于 2012-12-15T09:08:36.543 回答
3

我建议将 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
于 2012-12-15T09:11:11.467 回答