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.
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]];
Adding a new entry to a dictionary does two things (in addition to adding it to the dictionary, obviously):
NSCopying
protocolretain
s the value. This means that it needs to implement the NSObject
protocolIt'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).
I get my answer based on the comment of Zydeco:
You can convert between SEL and NSString using NSSelectorFromString and NSStringFromSelector
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With