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

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)


pix*_*x0r 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]
Run Code Online (Sandbox Code Playgroud)

  • 作为后续,NSValue是用于包装对象中的任何非对象类型的正确类.NSPoint,NSRect和NSSize都有专用的构造函数,数字类型由子类NSNumber包装,但您也可以包装任意结构,甚至包装对象而不保留它们.请注意...... NSValue用于*typed*数据.二进制数据的任意块应由NSData包装. (3认同)