Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSSelectorFromString

Is there something wrong with this code? I'm trying to set up some buttons by defining at run time the label, the callback selector, and, later, a pointer to the UIButton itself. But with this code, I get EXC_BAD_ACCESS. It gos away if I delete the line with NSSelectorFromString. But since this is just an object being added to the dictionary, I don't understand shy it fails.

NSMutableDictionary *attachButtonDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                        @"Attach To Job",@"keyForLabel",
                                        NSSelectorFromString(@"attachToJob"), @"keyForSelector",
                                        nil];
like image 892
Jim Avatar asked Jun 30 '26 13:06

Jim


2 Answers

a selector is not an objc object; a selector is an opaque representation of a method name.

the program will crash when adding it to the dictionary because it cannot be messaged. for example, it cannot be retained when added.

like image 148
justin Avatar answered Jul 03 '26 04:07

justin


You cannot store the selector into your NSDictionary.

Just store the string and when you build your button call NSSelectorFromString().

Best, Christian

Edit:

NSMutableDictionary *attachButtonDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                                @"Attach To Job",@"keyForLabel",
                                                @"attachToJob", @"keyForSelector",
                                                nil];

UIButton *fancyButton = [[UIButton alloc] init];
[fancyButton addTarget:self action:NSSelectorFromString([attachButtonDictionary objectForKey:@"keyForSelector"]) forControlEvents:UIControlEventTouchUpInside];
like image 26
cweinberger Avatar answered Jul 03 '26 03:07

cweinberger