iOS - Passing variable to view controller

Posted by gj15987 on Stack Overflow See other posts from Stack Overflow or by gj15987
Published on 2012-06-30T09:00:58Z Indexed on 2012/06/30 9:15 UTC
Read the original article Hit count: 217

Filed under:
|
|

I have a view with a view controller and when I show this view on screen, I want to be able to pass variables to it from the calling class, so that I can set the values of labels etc.

First, I just tried creating a property for one of the labels, and calling that from the calling class. For example:

SetTeamsViewController *vc = [[SetTeamsViewController alloc] init];
vc.myLabel.text = self.teamCount;
[self presentModalViewController:vc animated:YES];
[vc release];

However, this didn't work. So I tried creating a convenience initializer.

SetTeamsViewController *vc = [[SetTeamsViewController alloc] initWithTeamCount:self.teamCount];

And then in the SetTeamsViewController I had

- (id)initWithTeamCount:(int)teamCount {
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        // Custom initialization
        self.teamCountLabel.text = [NSString stringWithFormat:@"%d",teamCount];
    }
    return self;
}

However, this didn't work either. It's just loading whatever value I've given the label in the nib file. I've littered the code with NSLog()s and it is passing the correct variable values around, it's just not setting the label.

Any help would be greatly appreciated.

EDIT: I've just tried setting an instance variable in my designated initializer, and then setting the label in viewDidLoad and that works! Is this the best way to do this?

Also, when dismissing this modal view controller, I update the text of a button in the view of the calling ViewController too. However, if I press this button again (to show the modal view again) whilst the other view is animating on screen, the button temporarily has it's original value again (from the nib). Does anyone know why this is?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about ios