views:

127

answers:

3

Hi all, 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.

+1  A: 

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.

Williham Totland
You can convert between SEL and NSString using NSSelectorFromString and NSStringFromSelector
Zydeco
I use an singleton object for access the internet. and I have a method name: "getFooWithDelegate:callbackSelector:" and i want to add the delegate and callback to a dictionary of requests using an request UUID as the key.Can you explain more about adding the "name of the selector" you mentioned?
Thanh-Cong Vo
@athanhcong: again; it really does sound as if you should have a single specific name for the selector in question, e.g. `internetConnection:receivedFoo:withUUID:`, since you'll have to write the receiving method for receiving the object pretty specifically anyway. If that for whatever reason isn't an option; you would use `NSSelectorFromString()` and `NSStringFromSelector()` as outlined in Stephen Darlingtons post.
Williham Totland
@Williham: In my case, I use a third party library so I don't have the choice to implement the method name like you suggest (internetConnection:receivedFoo:withUUID:). The method: NSSelectorFromString() and NSStringFromSelector() work perfectly to me. Thank both of you a lot.
Thanh-Cong Vo
+2  A: 

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

Stephen Darlington
A: 

I get my answer based on the comment of Zydeco:

You can convert between SEL and NSString using NSSelectorFromString and NSStringFromSelector

Thanh-Cong Vo