Store selector as value in an NSDictionary

| | August 4, 2015

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

4 Responses to “Store selector as value in an NSDictionary”

  1. In case of using UILocalNotification the only way is to use NSSelectorFromString([dict objectForKey:@"foo"]). With valueWithPointer the app crashing when setting userInfo property of UILocalNotification object. Be careful.

  2. 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.

  3. Georg Fritzsche on November 30, -0001 @ 12:00 AM

    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];
    
  4. 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.

Leave a Reply