Objective c UITextfield.text返回null

Objective c UITextfield.text返回null,objective-c,ios,xcode,ios-4.2,Objective C,Ios,Xcode,Ios 4.2,假设iphone项目有以下代码: IBOutlet UITextField* numberDisplay; @property (strong,nonatomic) IBOutlet UITextField *numberDisplay; 在实现文件和 @综合数字显示 在实现文件中。同样在实施中的还有 -(IBAction)numberClicked:(id)sender { UIButton *buttonPressed = (UIButton

假设iphone项目有以下代码:

      IBOutlet UITextField* numberDisplay;
      @property (strong,nonatomic) IBOutlet UITextField *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建立的,并且通过查看inspector证明是建立的。即使作为测试,如果我添加行

    numberDisplay.text = @"a";
    NSLog(@"the value is %@",numberDisplay.text);   
    NSLog(@"the value is %@",numberDisplay);
我得到“两种情况下的值都是(空的)。有什么想法吗

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



感谢大家。我从头开始,现在一切正常。看起来我有一个错误标记的文件。

如果您将IBOutlet设置为Interface builder,则下一行将返回非空值。它将在.h文件中声明

IBOutlet UITextField* numberDisplay;
若您并没有将outlet设置为IB,它显然会返回null值,或者您必须通过编程方式对其进行初始化

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

看起来您可能没有在Interface Builder中正确设置
IBOutlets


查看我对的回答,基本上是一样的。

空对象可以接收选择器,它们会忽略它们并返回空对象。您遇到的情况如下:

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

确保文本字段不为空

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

@property (nonatomic, retain) UITextField *numberDisplay;
并将该行添加到.m中

@synthesize numberDisplay;

然后执行您所做的操作。这次您将不会得到空值。

尝试打印
numberDisplay
变量,而不是它的
text
属性。我确实怀疑您在其他地方没有初始化文本字段;因为您无法将变量分配给空对象,因此您会得到空值。如何初始化文本t字段。在属性检查器中,我尝试将文本和/或占位符以及两者都设置为0,以查看这是否有帮助,但它不起作用。您必须将.xib文件中的UiTextView与IBOutlet链接起来。我已将xib文件中的文本框拖到outlet,它确实注册了,因为在连接检查器中,它显示了引用的outlet作为我创建的文件的所有者。每个人都假设此
UITextField
未正确连接,这可能是真的,但您应该对此进行测试。这可以通过添加第三行来完成:
NSLog(@“文本字段为%@”,numberDisplay);
如果我将文本字段设置为“a”,该文本字段如何为空“为了证明他的回答,nil可以用nil回复任何消息。请检查您在IB中的连接是否合适..我已将xib文件中的文本框拖到出口,它确实注册了,因为在连接检查器中,它显示引用出口是我创建的文件的所有者IBOUtlet。首先将UITextField从库拖动到视图,然后按Ctrl键从文件的所有者拖动到视图中的textField,然后选择在.h文件中声明的textField。现在,保存并运行..希望这次它能工作