Why UILabel is not initialized?

自古美人都是妖i 提交于 2020-01-11 04:01:09

问题


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

The NSLog result is:

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

回答1:


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.

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.

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.



来源:https://stackoverflow.com/questions/11724003/why-uilabel-is-not-initialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!