我怎样才能将一个名称存储为NSDictionary值的函数调用?基本上我需要将String作为方法名称/调用进行类型转换。这可能吗?
[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"]]
这样的事情可能吗?
答案 0 :(得分:4)
不是这样,但您可以使用运行时/反射:
NSString *s = [thisCellContent objectForKey:@"callFunction"];
SEL sel = NSSelectorFromString(s);
[self performSelector:sel withObject:nil];
答案 1 :(得分: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