iPhone How-to:如何在NSDictionary中存放Selector

在iPhone中,Selector类型的定义是:

     typedef struct objc_selector     *SEL;

可见它本质上是一种指针。而NSDictionary存储的对象应该源自NSObject的对象。直接将SEL类型的值存放到NSDictionary中显然不大可能。在这种情况下,通常有两种做法:一是存放字符串,然后通过NSSelectorFromString从字符串得到SEL。第二种做法就是需要对SEL进行“打包”后存放到NSDictionary,获取时就进行相应的“解包”操作就可以了。本文关注第二种实现,其中存放和获取的代码分别如下:

 

// 存放Selector
SEL inSelector = @selector(sayHello:);
NSValue *selectorAsValue = [NSValue valueWithBytes:&inSelector objCType:@encode(SEL)];
id dict = [NSMutableDictionary dictionaryWithCapacity:3];
[dict setObject:selectorAsValue forKey:@"action"];

 

// 获取Selector
SEL outSelector;
[(NSValue *)[dict objectForKey:@"action"] getValue:&outSelector];
[self performSelector:outSelector withObject:@"…"];

你可能感兴趣的:(移动开发,iPhone,NSDictionary,selector,休闲)