为什么不初始化UILabel? [英] Why UILabel is not initialized?
问题描述
代码来自斯坦福CS193p.我添加了一个NSLog进行检查.标签似乎未初始化.有什么主意吗?
The code is from Stanford CS193p. I added a NSLog to check it out. The label seems not being initialized. Any idea?
@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)
推荐答案
您可能在显示视图控制器之前设置了问题字符串属性,大概是在prepareForSegue:中?此时,视图尚未加载,label属性仍为nil.
You are probably setting the question string property before you are displaying the view controller, presumably in prepareForSegue:? At this point, the view has not loaded and the label property will still be nil.
通过使用单独的字符串属性,您正在做正确的事情,您只是错过了必须同时在viewDidLoad中设置标签文本的步骤-此时,您的标签已从情节提要中实例化并可以使用.
You're doing the right thing by having a separate string property, you're just missing the step that you must also set the label's text in viewDidLoad - at this point your label has been instantiated from the storyboard and is ready to use.
如果要在调用viewDidLoad之前设置属性,则标签应该为nil.而且,如果您要从prepareForSegue设置属性,则该视图尚未加载.在需要将其显示在屏幕上之前,视图控制器不会加载其视图和子视图,并且只有在执行segue时才会发生这种情况-您可以猜测,prepareForSegue在segue执行之前就完成了.
If you're setting properties before viewDidLoad is called, the label being nil is expected. And if you're setting properties from prepareForSegue, the view won't have been loaded yet. A view controller won't load it's view and subviews until it needs to display them on screen, and this doesn't happen until the segue is being performed - and as you can guess, prepareForSegue is done before the segue is performed.
这篇关于为什么不初始化UILabel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!