简体   繁体   中英

Cannot assign to view controller's property after instantiating from storyboard

I'm instantiating a view controller from the storyboard with this code:

CalloutViewController *calloutVC = (CalloutViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"CalloutViewController"];

and trying to assign to it's property nameLabel, declared here in its header:

@interface CalloutViewController : UIViewController

@property (strong, nonatomic) IBOutlet UILabel *nameLabel;
...
@end

using

calloutVC.nameLabel.text = @"test";

However, after the assignment, the property is still nil.

It's because the IBOutlet is not loaded yet. You need to create a NSString property and assign your value to it. And in your CalloutViewController 's viewDidLoad assign the value to your IBOutlet .

Like:

@interface CalloutViewController : UIViewController

@property (nonatomic, weak) IBOutlet UILabel *nameLabel;
@property (nonatomic, copy) NSString *nameValue;
...
@end

And in your viewDidLoad

- (void)viewDidLoad
{
   [super viewDidLoad];
   self.nameLabel.text = self.nameValue;
   ...
}

And assign the property like:

calloutVC.nameValue = @"test";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM