UITextfield.text返回null

时间:2011-12-03 04:00:52

标签: objective-c ios xcode ios-4.2

假设有一个iphone项目的代码:

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

在实施文件和

@synthesize numberDisplay;

在实施文件中。同样在实施中

     -(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 ];  
    }

   }

当我运行应用程序时,UITextfield中没有显示任何显示,即使连接是使用IB进行的,并且已经证明是通过查看检查器进行的。即使作为测试,如果我添加行

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

我得到“两个案例中的值都是(null)。任何想法。

有人可以告诉我这两行有什么问题吗?谢谢。


感谢所有人。我从零开始,现在一切正常。看起来我的文件标签错误。

4 个答案:

答案 0 :(得分:2)

Null对象可以接收选择器并忽略它们并返回null对象。你遇到的情况是这样的:

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

确保文本字段不为空

答案 1 :(得分:1)

如果已将IBOutlet设置为“接口”构建器,则以下行将返回非空值。它将在.h文件中声明。

IBOutlet UITextField* numberDisplay;

如果您没有为IB设置插座,它显然会返回空值,或者您必须通过编程方式对其进行初始化。

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

答案 2 :(得分:0)

您可能无法在Interface Builder中正确设置IBOutlets

查看我对this question的回答,基本上是相同的。

答案 3 :(得分:0)

您必须通过以下方式正确合成文本字段: - 在.h

中添加该行
@property (nonatomic, retain) UITextField *numberDisplay;

并在.m

中添加该行
@synthesize numberDisplay;

然后做你做的。这次你不会得到空值。

相关问题