UIButton调用选择器崩溃了应用程序

时间:2012-05-04 15:56:34

标签: objective-c ios cocoa-touch cocoa

在我的应用程序中,我有一个按钮,它是已在.h文件中声明的实例变量。 现在在分配了一个目标指向它并实际按下按钮后,应用程序崩溃,在调试器中给出了以下输出:

-[__NSCFString handleActionSheet:]: unrecognized selector sent to instance 0x9090330
2012-05-04 17:51:02.646 financeAppV2[2595:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString handleActionSheet:]: unrecognized selector sent to instance 0x9090330'
*** First throw call stack:
(0x13d1022 0x1562cd6 0x13d2cbd 0x1337ed0 0x1337cb2 0x13d2e99 0x1e14e 0x1e0e6 0xc4ade 0xc4fa7 0xc3d8a 0x2dfa1a 0x13a599e 0x133c640 0x13084c6 0x1307d84 0x1307c9b 0x12ba7d8 0x12ba88a 0x1b626 0x29dd 0x2945)
terminate called throwing an exceptionCurrent language:  auto; currently objective-c

我的代码如下:

saveButton=[UIButton buttonWithType:UIButtonTypeCustom];
[saveButton setBackgroundImage:[UIImage imageNamed:@"intervalbutton"] forState:UIControlStateNormal];
[saveButton setBackgroundImage:[UIImage imageNamed:@"intervalbuttonpressed"] forState:UIControlStateHighlighted];
saveButton.alpha=.8;
saveButton.frame= frame;
UILabel* label=[[UILabel alloc]initWithFrame:CGRectMake(0, 2, saveButton.frame.size.width, 21)];
[saveButton addSubview:label];

[saveButton addTarget:self action:@selector(handleActionSheet:) forControlEvents:UIControlEventTouchDown];

[self.view addSubview:saveButton];


-(void)handleActionSheet:(id)sender{
NSLog(@"working");

}

为什么应用可能崩溃的任何想法?

3 个答案:

答案 0 :(得分:5)

如果没有看到代码的其余部分,则很难具体,但self未正确保留。

您正确设置了按钮(据我所知)并将目标指向self。不幸的是,当您按下按钮self超出范围并且NSString使用相同的内存时。当您发送handleActionSheet:消息字符串时,iOS会感到惊讶。

答案 1 :(得分:1)

您正在向initAllIVars:对象(可能是__NSCFString)发送名为NSString的消息。

搜索该消息并尝试找出接收消息的对象为NSString的原因。

答案 2 :(得分:0)

刚刚测试过你的代码,它确实有效。也许框架没有正确设置

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    UIButton *saveButton = [[UIButton alloc] init];
    saveButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [saveButton setBackgroundImage:[UIImage imageNamed:@"intervalbutton"] forState:UIControlStateNormal];
    [saveButton setBackgroundImage:[UIImage imageNamed:@"intervalbuttonpressed"] forState:UIControlStateHighlighted];
    saveButton.alpha=.8;
    saveButton.frame= CGRectMake(5, 5, 200, 40);
    UILabel* label=[[UILabel alloc]initWithFrame:CGRectMake(0, 2, saveButton.frame.size.width, 21)];
    label.text = @"Hello";
    [saveButton addSubview:label];

    [saveButton addTarget:self action:@selector(handleActionSheet:) forControlEvents:UIControlEventTouchDown];

    [self.view addSubview:saveButton];

}

-(void)handleActionSheet:(id)sender{
    NSLog(@"working");
}
相关问题