此代码位于UITableViewController子类viewDidLoad方法中。 UITableViewController子类包含一个测试方法。
它崩溃而没有抛出异常。
id dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys: @"some text", @"text", @selector(test), @"selector", nil]
答案 0 :(得分:14)
pix0r的解决方案很好,但我通常更喜欢使用字符串,因为它们对序列化更具弹性,并且使字典更容易在调试输出中读取。
// Set selector
SEL inSelector = @selector(something:);
NSString *selectorAsString = NSStringFromSelector(inSelector);
id dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"some text", @"text", selectorAsString, @"selector", nil];
// Retrieve selector
SEL outSelector = NSSelectorFromString([dict objectForKey:@"selector"]);
答案 1 :(得分:5)
使用NSValue
包装选择器:
// Set selector
SEL inSelector = @selector(something:);
NSValue *selectorAsValue = [NSValue valueWithBytes:&inSelector objCType:@encode(SEL)];
id dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"some text", @"text", selectorAsValue, @"selector", nil];
// Retrieve selector
SEL outSelector;
[(NSValue *)[dict objectForKey:@"selector"] getValue:&outSelector];
// Now outSelector can be used as a selector, e.g. [self performSelector:outSelector]