NSSelectorFromString

Is there something wrong with this code? I am trying to customize some buttons by defining at runtime a label, callback selector and, later, a pointer to UIButton itself. But with this code, I get EXC_BAD_ACCESS. If you delete the line using NSSelectorFromString, it will disappear. But since this is just an object added to the dictionary, I do not understand that it is shy.

NSMutableDictionary *attachButtonDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                        @"Attach To Job",@"keyForLabel",
                                        NSSelectorFromString(@"attachToJob"), @"keyForSelector",
                                        nil];
+3
source share
3 answers

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

The program will crash when you add it to the dictionary, because it cannot be sent to the message. for example, it cannot be saved when added.

+4
source

selector NSDictionary.

NSSelectorFromString().

, 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];
+4

While you cannot save the selector in the dictionary, you can wrap it in NSValue.

SEL fooSel = @selector(foo);
NSValue *selWrapper = [NSValue valueWithPointer:fooSel];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:selWrapper 
                                                               forKey:@"foo"];
SEL myFooSel = [[dict objectForKey:@"foo"] pointerValue];
[obj performSelector:myFooSel];
+1
source

All Articles