覆盖viewDidLoad中的现有值

时间:2014-01-05 17:09:20

标签: ios objective-c viewdidload

有没有人可以帮我解决问题?我正在用游戏帮助朋友,我们仍然坚持如何覆盖现有的整数。问题在于xCode中的Objective-C。

有两个viewControllers frontPage和secondPage。在frontPage中,我们在viewDidLoad方法中为startingScore分配100。然后我们去第二页,从第二页开始我们回来。我们想在frontPage中使用第二页的startingScore,但是它会被viewDidLoad覆盖。

这是我们从frontPage(或第一个View Controller)获得的:

- (void)viewDidLoad
{
    startingScore = 100;
    mylabel1.text = [NSString stringWithFormat:@"%d", startingScore];
    [super viewDidLoad];
// Do any additional setup after loading the view.
    NSLog(@"Current value of newscore is: %d",startingScore);

}

这是来自SecondViewController的代码:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    frontPage *destination = [segue destinationViewController];
    destination.startingScore = 5000;
    destination.mylabel2.text = [NSString stringWithFormat:@"%d", destination.startingScore];
    NSLog(@"Current Value of destination.newscore is: %d",destination.startScore);  
}

有人能帮助我吗?

谢谢,

Sam x。

2 个答案:

答案 0 :(得分:1)

如果您希望在从那时起在其他地方首次创建和管理frontPage视图控制器时将startingScore设置为100,则可以将startingScore的初始化移动到init函数中:

- (id)init
{
    if(self = [super init]) {
        // ...
        startingScore = 100;
    }
    return self;
}

答案 1 :(得分:0)

我想我得到了线索。在这里,您将startingScore的值更改为2次。首先,您要在viewDidLoad中将其值设置为500。然后,您将使用-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender方法从500更改为5000。现在,当您返回frontpage时,viewDidLoad再次调用frontPage方法。因此startingscore的值再次变为500.您可以使用NSLog函数进行检查。我很确定这就是这里发生的事情。

纠正问题的建议

  1. startingScore
  2. init中发起frontPage
  3. 从其他班级管理startingScore
  4. 修改只需将以下代码粘贴到FrontPage&的VC中。从startingScore = 500;方法

    中删除viewDidLoad
    - (id)init
    {
        if(self = [super init])
     {
            startingScore = 500;
        }
        return self;
    }