使用selector作为参数的错误

时间:2012-08-11 22:08:11

标签: objective-c xcode

我正在设置UINavigationBar并且按钮有问题。当我这样做时:

-(void)addLeftButton:(NSString *)titl
{
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:titl style:UIBarButtonItemStyleBordered target:self action:@selector(haikuInstructions)];
self.titleOfNavItem.leftBarButtonItem = button;
}

然后一切都很好。但如果我这样做:

-(void)addLeftButton:(NSString *)titl callingMethod:(NSString *)method
{
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:titl style:UIBarButtonItemStyleBordered target:self action:@selector(method)];
self.titleOfNavItem.leftBarButtonItem = button;
}

并以另一种方法调用该方法:

[self addLeftButton:@"Instructions" callingMethod:@"haikuInstructions"];

我收到unrecognized selector错误。关于我做错了什么的想法?

1 个答案:

答案 0 :(得分:3)

您应该使用NSSelectorFromString(NSString *aSelectorName)

UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:titl style:UIBarButtonItemStyleBordered target:self action:NSSelectorFromString(method)];

修改 详细说明,@selector指令将在字面上对括号内的名称进行处理。更重要的是,它不会检查该方法是否真的存在。这意味着,如果您使用@selector(method)并且还有变量NSString *method = @"haikuInstructions",则不会指向名为"haikuInstructions"的选择器,而是指向名为"method"的选择器。