如何让NSDictionary包含一个选择器作为其值之一?

时间:2009-07-23 21:49:10

标签: objective-c

此代码位于UITableViewController子类viewDidLoad方法中。 UITableViewController子类包含一个测试方法。

它崩溃而没有抛出异常。

id dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys: @"some text", @"text", @selector(test), @"selector", nil]

2 个答案:

答案 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]