简体   繁体   中英

iPhone - NSString value not being set

Inside of a UIViewController, I am executing the following:


TVController* stopTimes = [ [ TVController alloc ] initWithStyle: UITableViewStyleGrouped ];
stopTimes.tableView.frame = CGRectMake( 0, 180, 320, 280 );
stopTimes.tableView.backgroundColor = [ UIColor whiteColor ];
stopTimes.theID = stopID;
[ self.view addSubview: stopTimes.tableView ];

where TVController is a UITableViewController.

Inside the TVController class, I have an NSString property called theID which has been synthesized. I get no errors when doing 'stopTimes.theID = stopID' above, and the TableView appears as expected.

In 'viewDidLoad' of this TVController class, I am simply attempting to NSLog 'theID' to show that it worked, but it is (null) no matter what I do.

However, I tried setting a cell's text to 'theID' and it worked just fine.

So why is 'theID' set properly when setting up a cell, but not in viewDidLoad?

viewDidLoad will be called immediately after the view is loaded, either from your NIB or your implementation of loadView. The view is loaded the first time that the view property of the view controller is accessed, not when the view controller is allocated or at some later point.

This means that loadView (the default implementation of which loads your NIB, if you have one) and then viewDidLoad are called the first time on that second line because you are accessing the tableView property of your view controller, and that of course occurs before you actually set a value for the theID property of the view controller. Of course, by the time your table content is loaded (which doesn't happen until the table view actually appears unless you call -reloadContent yourself elsewhere), your theID property has been set.

You can very simply test yourself this by setting two breakpoints in the debugger - one on the third line of your code snippet above where you set the theID property, and one on your NSLog() call in viewDidLoad. You will see that the latter breakpoint is triggered first.

PS Welcome to Stack Overflow! Don't forget to read the FAQ and mark accepted answers for your questions (if they're good answers worth accepting, of course).

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