tags:

views:

197

answers:

2

Is there a way to store a selector in an NSDictionary, without storing it as an NSString?

+7  A: 

SEL is just a pointer, which you could store in an NSValue:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: 
                       [NSValue valueWithPointer:@selector(foo)], @"foo",
                       nil];

To get the selector back, you can use:

SEL aSel = [[dict objectForKey:@"foo"] pointerValue];
Georg Fritzsche
Maybe also mention that to get the SEL back, you have to do: `SEL *aSel = [[dict objectForKey:@"foo"] pointerValue];`
dreamlax
Good point. @dreamlax
Georg Fritzsche
When I retrieve SEL as you suggest and try self performSelector:*aSel withObject:nil afterDelay:0.0]; I get: EXC_BAD_ACCESS. The correct way of retrieving them is SEL aSel = [[dict objectForKey:@"foo"] pointerValue];[self performSelector:aSel withObject:nil afterDelay:0.0];
nacho4d
@nacho: Right, fixed.
Georg Fritzsche
+1  A: 

An NSDictionary is really just a CFDictionary that retains and releases all keys and values. If you create a CFDictionary directly, you can set it up to not retain and release values. You can typecast a CFDictionaryRef to an NSDictionary * and vice versa.

drawnonward
I do this quite a bit for when I have Foundation objects as keys but non-Foundation objects as values.
dreamlax