Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add method selector into a dictionary

I want to add a selector into a dictionary (the main purpose is for identifying the callback method and delegate after finish doing something)

But I find that I can not do that, the program will get an error "EXC_BAD_ACCESS". Are there any other way for me to add that method selector to a dictionary? Thanks for your help.

like image 838
KONG Avatar asked Feb 01 '10 09:02

KONG


3 Answers

I know this question was answered a long time ago, but just in case anyone stumbles upon it like I did...

The combination of NSStringFromSelector and NSSelectorFromString as answered above is probably the best way to go. But if you really want to, you can use a selector as a value or key in an NSDictionary.

A selector (type SEL) is implemented as a pointer to a struct in Apple's Objective-C runtimes. A pointer cannot be used directly in a dictionary, but a pointer can be wrapped in an NSValue object that can be used.

Using this method you can store a selector as a value in a dictionary using code like this:

dictionary = 
  [NSDictionary dictionaryWithObject:[NSValue valueWithPointer:selector]
                              forKey:key];

A selector can be retrieved using code like this:

SEL selector = [[dictionary objectForKey:key] pointerValue];

Similarly for using a selector as a key:

dictionary = 
  [NSDictionary dictionaryWithObject:value
                              forKey:[NSValue valueWithPointer:selector]];

value = [dictionary objectForKey:[NSValue valueWithPointer:selector]];
like image 150
JimInAus Avatar answered Oct 21 '22 21:10

JimInAus


Adding a new entry to a dictionary does two things (in addition to adding it to the dictionary, obviously):

  1. It takes a copy of the key value. This means that the the key object must implement the NSCopying protocol
  2. retains the value. This means that it needs to implement the NSObject protocol

It's probably the second that's causing your EXC_BAD_ACCESS.

There are at least two ways around this.

Firstly, rather than adding the selector you could add the instance of the class that implements the selector to your dictionary. Usually your class will inherit from NSObject and it will work fine. Note that it will retain the class though, maybe not what you want.

Secondly, you can convert a selector to a string (and back again) using NSSelectorFromString and NSStringFromSelector (docs are here).

like image 22
Stephen Darlington Avatar answered Oct 21 '22 20:10

Stephen Darlington


I get my answer based on the comment of Zydeco:

You can convert between SEL and NSString using NSSelectorFromString and NSStringFromSelector

like image 2
KONG Avatar answered Oct 21 '22 21:10

KONG