Take a random Number from one ViewController and use it in a second ViewController - Update
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 = [[TweetViewCont开发者_Go百科roller 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];
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;
}
精彩评论