Is there anybody out there who could help me with a problem? I'm helping a friend with a game and we're stuck on how to overwrite an existing integer. The problem is with Objective-C in xCode.
There are two viewControllers frontPage and secondPage. In the frontPage we assign 100 to the startingScore in the viewDidLoad method. Then we go out to the secondPage and from the secondPage we come back. We want to use the startingScore from the secondPage in frontPage, but it's getting overwritten with viewDidLoad.
This is what we have from frontPage (or first 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);
}
This the code from the 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);
}
Can anybody help me?
Thanks,
Sam x.
I think I got the clue. Here you are changing value of startingScore
2 times. First you are setting its value to 500 in viewDidLoad
. Then you are changing from 500 to 5000 in -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
method. Now when you are coming back to frontpage
, the viewDidLoad
method is being called again for frontPage
. so value of startingscore
is again turning into 500. You can check it by using NSLog
function. I am pretty sure that's what happening here.
Suggestions to rectify the problem
startingScore
in init
of frontPage
startingScore
from another class.Edit Just paste code written below in VC of your FrontPage
& remove startingScore = 500;
from your viewDidLoad
Method
- (id)init
{
if(self = [super init])
{
startingScore = 500;
}
return self;
}