views:

84

answers:

1

Hi, I have two ViewControllers: The RedButtonViewController and the TweetViewController. The RedButtonViewController generates random numbers in Textlabels and I want to use the number or the label with the TweetViewController. How can I make this?

Thanks for your help!

My TweetViewController will be opened with this code in the RedButtonViewController:

- (IBAction)TweetViewController:(id)sender {
    TweetViewController *Tweet = [[TweetViewController alloc] initWithNibName:nil bundle:nil];
    [self presentModalViewController:Tweet animated:YES];
}

Here is an exemple of how I generate the random number:

- (IBAction)pushRedButton:(UIButton *)sender { 

    int ZahlDerToten;
    ZahlDerToten = arc4random() % 1000000;  

    outputLabel.text = [NSString stringWithFormat:@"You killed %d people.", ZahlDerToten];  
+1  A: 

Create a property on the TweetViewController and set it before presenting it:

- (IBAction)TweetViewController:(id)sender {
    // Note: don't put leading capitals on a local variable
    TweetViewController *tweet = [[TweetViewController alloc] initWithNibName:nil bundle:nil];
    tweet.randomNumber = [self generateRandomNumber];
    [self presentModalViewController:tweet animated:YES];
    // Note: You were leaking the view controller
    [tweet release];
}

Another solution (and how I usually do this kind of thing) is to create a new initializer called -initWithNumber: (probably something a little more descriptive than "number") and call it like this:

- (IBAction)TweetViewController:(id)sender {
    TweetViewController *tweet = [[TweetViewController alloc] initWithNumber:[self generateRandomNumber]];
    [self presentModalViewController:tweet animated:YES];
    [tweet release];
}

-initWithNumber would then look something like:

- (TweetViewController *)initWithNumber:(NSInteger)number {
    self = [super initWithNibName:nil bundle:nil];
    if (self != nil) {
        self.number = number;
    }
    return self;
}
Rob Napier
Hi thanks for your answer. I tried your second method and always when I use initWithNumber he says in the line: self.number = outputlabel; Request for member ´number´is something noot a structure or unionMaybe the problem is, that I dont know what I have to replace in your code and what not...i put a exemple of how i generate the random number above in the question.
Flocked
In this code I assumed there would be a property called "number," just as an example; I'm assuming that the TweetViewController has some ivar holding this number. You almost certainly shouldn't be passing the label itself. Don't use labels to store data. Store data in ivars; set labels' values from those ivars. This is a key feature of the Model-View-Controller pattern that Cocoa relies on. So if you changed "number" above to be a UILabel, don't do that. It should an NSUInteger in your example, and there should be a property like countOfKilledPeople.
Rob Napier