Tuesday, 28 June 2011

Crash caused by missing ":"

Was testing an array of buttons all using the same "buttonPressed" method to handle the click action, and based on tag value to work out which button been clicked. It keep crashing whenever I clicked any of the buttons and couldn't work out why.


    UIButton *button;
    
    [self createNormalButton: button 
                      atPosX: locX
                      atPosY: locY 
                   withWidth: widthValue
                  withHeight: heightValue  
                 withBGColor: [UIColor clearColor
              withTitleColor: [UIColor clearColor
                     withTag: tagValue 
                   withTitle@""
                  withSelfIDself 
                withActionID@selector(buttonPressed)
                   ifEnabledYES
                      inViewself.view];



- (IBAction) buttonPressed: (id) sender
{
    
    int whichButton;
    
    whichButton = (int) ((UIButton *)sender).tag;
    
    NSLog(@"Clicked button tag=%d",whichButton);
}



The error message is as below:


2011-06-28 23:35:57.374 NoNIBTest1[1758:207] -[TestBedViewController buttonPressed]: unrecognized selector sent to instance 0x4e07340
2011-06-28 23:35:57.377 NoNIBTest1[1758:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TestBedViewController buttonPressed]: unrecognized selector sent to instance 0x4e07340'



Took me a while to realise because this "buttonPressed" method is now accepting/expecting an extra parameter "(id) sender", I have to add an extra ":" at the end when passing the selector ID for action.

So it should be "@selector(buttonPressed:)" with the extra ":" at the end. Quite strange compared to what I learned before in other programming languages.


    UIButton *button;
    
    [self createNormalButton: button 
                      atPosX: locX
                      atPosY: locY 
                   withWidth: widthValue
                  withHeight: heightValue  
                 withBGColor: [UIColor clearColor
              withTitleColor: [UIColor clearColor
                     withTag: tagValue 
                   withTitle: @""
                  withSelfID: self 
                withActionID: @selector(buttonPressed:)
                   ifEnabled: YES
                      inViewself.view];
    


No comments:

Post a Comment