我有两个ViewControllers:RedButtonViewController和TweetViewController。 RedButtonViewController在Textlabels中生成随机数,我想在TweetViewController中使用数字或标签。我该怎么做?
感谢您的帮助!
我的TweetViewController将在RedButtonViewController中使用此代码打开:
- (IBAction)TweetViewController:(id)sender {
TweetViewController *Tweet = [[TweetViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:Tweet animated:YES];
}
以下是我如何生成随机数的例子:
- (IBAction)pushRedButton:(UIButton *)sender {
int ZahlDerToten;
ZahlDerToten = arc4random() % 1000000;
outputLabel.text = [NSString stringWithFormat:@"You killed %d people.", ZahlDerToten];
答案 0 :(得分:1)
在TweetViewController上创建一个属性并在呈现之前进行设置:
- (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];
}
另一种解决方案(以及我通常如何做这种事情)是创建一个名为-initWithNumber:
的新初始化程序(可能比“数字”更具描述性),并将其称为:
- (IBAction)TweetViewController:(id)sender {
TweetViewController *tweet = [[TweetViewController alloc] initWithNumber:[self generateRandomNumber]];
[self presentModalViewController:tweet animated:YES];
[tweet release];
}
然后 -initWithNumber
看起来像:
- (TweetViewController *)initWithNumber:(NSInteger)number {
self = [super initWithNibName:nil bundle:nil];
if (self != nil) {
self.number = number;
}
return self;
}