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):
- It takes a copy of the key value. This means that the the key object must implement the
NSCopying
protocol retain
s the value. This means that it needs to implement theNSObject
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).
I get my answer based on the comment of Zydeco:
You can convert between SEL and NSString using NSSelectorFromString and NSStringFromSelector
The common idiom in Obj-C is to have specific names for callbacks for specific events. (Such parserDidBeginDocument:
from NSXMLParserDelegate
). If you really need to be able to specify the names, it is likely that your only recourse is to add the names of the selectors as @"mySelector:withArgument:context:"
or somesuch.
精彩评论