为什么UILabel没有初始化?

代码来自Stanford CS193p。 我添加了一个NSLog检查出来。 标签似乎没有被初始化。 任何想法?

@interface AskerViewController() <UITextFieldDelegate> @property (weak, nonatomic) IBOutlet UILabel *questionLabel; @property (weak, nonatomic) NSString *question; @end @implementation AskerViewController @synthesize questionLabel = _questionLabel; @synthesize question = _question; - (void)setQuestion:(NSString *)question { _question = question; self.questionLabel.text = question; NSLog(@"label is %@", self.questionLabel); } @end 

NSLog的结果是:

 2012-07-31 01:56:45.177 Kitchen Sink[23931:f803] label is (null) 

在显示视图控制器之前,您可能正在设置问题string属性,据推测在prepareForSegue:? 在这一点上,视图没有加载,标签属性仍然是零。

你做了正确的事情,有一个单独的string属性 ,你只是错过了你也必须在viewDidLoad中设置标签的文本的步骤 – 在这一点上你的标签已经从故事板实例化,并准备使用。

如果在调用viewDidLoad之前设置属性,则标签为空。 如果你正在从prepareForSegue设置属性,视图将不会被加载。 视图控制器不会加载它的视图和子视图,直到它需要在屏幕上显示它们,直到执行了这个循环才会发生这种情况 – 正如你所猜测的,prepareForSegue是在执行该循环之前完成的。