Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store selector as value in an NSDictionary

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

like image 369
synic Avatar asked May 12 '10 20:05

synic


3 Answers

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];
like image 200
Georg Fritzsche Avatar answered Oct 11 '22 14:10

Georg Fritzsche


An alternative to Georg's solution would be to convert the selector into an NSString before storing it the NSDictionary:

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

SEL selector = NSSelectorFromString([dict objectForKey:@"foo"]);

This technique, though uses more memory, gives you the ability to serialize the entire NSDictionary as a string via libraries like JSONKit.

like image 10
David H Avatar answered Oct 11 '22 15:10

David H


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.

like image 6
drawnonward Avatar answered Oct 11 '22 15:10

drawnonward