UITextfield.text returns null

stephen kronwith picture stephen kronwith · Dec 3, 2011 · Viewed 7.6k times · Source

Assume there's code for an iphone project that is :

      IBOutlet UITextField* numberDisplay;
      @property (strong,nonatomic) IBOutlet UITextField *numberDisplay;

in implementation file and

@synthesize numberDisplay;

in implementation file. Also in implementation is

     -(IBAction)numberClicked:(id)sender {  
     UIButton *buttonPressed = (UIButton *)sender;  
    int val = buttonPressed.tag;  
     if ( [numberDisplay.text compare:@"0"] == 0 ) {  
    numberDisplay.text =[NSString  stringWithFormat:@"%d", val ];  

  } else {  
      numberDisplay.text = [NSString  
                     stringWithFormat:@"%@%d", numberDisplay.text, val ];  
    }

   }

When I run the app there is no display shown in the UITextfield, even though the connections were made with IB and is proven to be made by viewing the inspector. Even as a test if I add the lines

    numberDisplay.text = @"a";
    NSLog(@"the value is %@",numberDisplay.text);   
    NSLog(@"the value is %@",numberDisplay);

I get " the value is (null) in both cases.Any ideas.

Can someone please tell me what is wrong with these two lines?. Thank you.


Thanks to all. I started from scratch and now all works. Looks like I had a mislabeled file.

Answer

Dani picture Dani · Dec 3, 2011

Null objects can receive selectors and they ignore them and return null object. the case you encounter is like this:

[(UITextField*)nil setText:@"a"];
NSLog(@"the value is %@", [(UITextField*)nil text]);

Make sure the text field is not null