Reputation: 3672
[I have this working, but I don't understand why my "fix" to make it work did so.]
As part of a learning exercise, I'm creating a simple table. When the user selects a cell in the table, I want it to go a second UIViewController. THe second UIViewController has a label that shows the text from the cell selected.
The "parent" class has this method to create the child & set the text:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
child = [[WDRViewControllerFirstChild alloc] initWithNibName:nil bundle:nil];
child.title = [colors objectAtIndex:indexPath.row];
child.labelText = [colors objectAtIndex:indexPath.row];
[self.navigationController pushViewController:child animated:YES];
}
Then in WDRViewControllerFirstChild, I have two methods. If I approach it this way, everything works.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 50)];
colorMap = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil] forKeys:[NSArray arrayWithObjects:@"red", @"green", @"blue", nil]];
// Adding the subview here won't work. Why?
// [self.view addSubview:label];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.view addSubview:label];
label.text = labelText;
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor whiteColor];
self.view.backgroundColor = [colorMap objectForKey:labelText];
}
Originally, I assigned the child to the subview in the init call, however that didn't work. That is, the label of the text wouldn't properly show the text of the item that had been selected. (It would be blank.)
I added some NSLog calls and additionally found that if I move the addSubview call from viewDidLoad to the init, the value of labelText is null. However, in the form above, it's properly set.
I'm happy it's working, but I don't understand why one work & the other does. In particular, I'm really confused why setting labelText works based upon where I call addSubview.
Any insights?
Upvotes: 0
Views: 238
Reputation: 43330
-addSubview
will only work if the view is actually completely loaded out of the XIB, else it sends a call to nil and produces nil. By the time -initWithNibName:bundle:
is called, the OS is most likely defrosting (literally) the XIB you specified and setting it up, so the view property is nil. at -viewDidLoad
you can be reasonably assured as to the existence of the view, so that's where most setup work is done. as for the (NULL) label text, whatever the iVar labelText
is, you didn't instantiate it. Remove that line.
Upvotes: 1