Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableDictionary with UIButton* as keys - iPhone development

I'm new to iPhone development and I have a question that may have a very simple answer. I am trying to add buttons to a view and these buttons are associated with a custom class that I defined. When I add the buttons to the view, I would like to know what class these buttons correspond to. This is because when I press the button, I need to get some information about the class, but the receiver of the message is another class. I couldn't find information about an error that I'm getting on the web. The problem I have is that I'm trying to create an NSMutableDictionary where the keys are of type UIButton* and the values are of my custom type:

   // create button for unit
   UIButton* unitButton = [[UIButton alloc] init];
   [sourceButtonMap setObject:composite forKey:unitButton];

Of course, the sourceButtonMap is defined in the class and initialized in the init function as sourceButtonMap = [[NSMutableDictionary alloc] init];

The error I get when I try to add the key-value pair is:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[UIButton copyWithZone:]: unrecognized selector sent to instance 0x3931e90'

Is this happening because I can't store UIButton* as keys? Can anyone point me why I'm getting this error? Thank you all,

aa

like image 628
Alejandro A. Avatar asked May 12 '10 15:05

Alejandro A.


2 Answers

One way I found was to use construct an NSValue to use as the key. To create the that use:

[NSValue valueWithNonretainedObject:myButton].

The caveat here seems to be that if the button is garbage collected, the key will hold an invalid reference.

You can get the reference to the UIButton again while looping through the Dictionary like so:

for (NSValue* nsv in myDict) {
    UIButton* b = (UIButton*)[nsv nonretainedObjectValue];
    ...
}
like image 175
Arpit Avatar answered Dec 01 '22 01:12

Arpit


From Apple docs:

The key is copied (using copyWithZone:; keys must conform to the NSCopying protocol).

UIButton does not conform to the NSCopying protocol and so you cannot use it as a key in NSDictionary

like image 23
pheelicks Avatar answered Nov 30 '22 23:11

pheelicks