10 objective-c
此代码位于UITableViewController子类viewDidLoad方法中.UITableViewController子类包含一个测试方法.
它崩溃而没有抛出异常.
id dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys: @"some text", @"text", @selector(test), @"selector", nil]
Run Code Online (Sandbox Code Playgroud)
Rob*_*ier 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"]);
Run Code Online (Sandbox Code Playgroud)
使用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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2500 次 |
| 最近记录: |