Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextfield.text returns null [closed]

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.

like image 642
stephen kronwith Avatar asked Dec 03 '11 04:12

stephen kronwith


2 Answers

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

like image 160
Dani Avatar answered Oct 12 '22 23:10

Dani


Following line will return non null value if you have set IBOutlet to Interface builder. It will declared in .h file.

IBOutlet UITextField* numberDisplay;

If you are not setting outlet to an IB, it will obviously return null value or you have to initialize it by programmatically.

UITextField *numberDisplay = [[UITextField alloc] initWithFrame:CGRectMake(10,10, 100,30)];
numberDisplay.font = [UIFont fontWithName:@"Verdana" size:12.0];
numberDisplay.background = [UIColor clearColor];
numberDisplay.text = @"123456789";
[self.view addSubview:numberDisplay];
NSLog(@"the value is %@",numberDisplay.text); // returns 123456789
like image 42
alloc_iNit Avatar answered Oct 12 '22 23:10

alloc_iNit