Reputation: 2207
I'm setting up a UINavigationBar and am having trouble with the buttons. When I do this:
-(void)addLeftButton:(NSString *)titl
{
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:titl style:UIBarButtonItemStyleBordered target:self action:@selector(haikuInstructions)];
self.titleOfNavItem.leftBarButtonItem = button;
}
Then everything turns out fine. But if I do this:
-(void)addLeftButton:(NSString *)titl callingMethod:(NSString *)method
{
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:titl style:UIBarButtonItemStyleBordered target:self action:@selector(method)];
self.titleOfNavItem.leftBarButtonItem = button;
}
and call the method in another method like this:
[self addLeftButton:@"Instructions" callingMethod:@"haikuInstructions"];
I get an unrecognized selector
error. Any thoughts about what I'm doing wrong?
Upvotes: 0
Views: 47
Reputation: 5539
You should use NSSelectorFromString(NSString *aSelectorName)
:
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:titl style:UIBarButtonItemStyleBordered target:self action:NSSelectorFromString(method)];
EDIT:
To elaborate, @selector
directive will treat name between parenthesis literally. What's more, it won't check if that method really exists. This means if you use @selector(method)
and have also variable NSString *method = @"haikuInstructions"
you won't point to selector named "haikuInstructions"
, but to selector named "method"
.
Upvotes: 3