The problem I get when I use the codes below is that the totalScore only updates when the viewDidLoad method in the secondViewController is called. So if I press the addOne button twice in a row the retrievingString is the same both times so it will just add one to the same existing value, because it haven’t been updated in the secondViewController. How can I manage to update the totalScore in secondViewController each time the addOne button is pressed in firstViewController
firstViewController:
-(void)saveString:(NSString *)myString {
[[NSUserDefaults standardUserDefaults] setObject:myString forKey:@"firstScore"];
}
-(NSString *)retrieveString {
NSString *recoveredString = [[NSUserDefaults standardUserDefaults]objectForKey:@"totalScore"];
return recoveredString;
}
-(IBAction) addOne {
NSString *totalScore = [self retrieveString];
NSInteger totalScoreInt = [totalScore intValue];
NSInteger newScore = totalScoreInt+1;
NSString *newScoreString = [NSString stringWithFormat:@"%i", newScore];
[self saveString:newScoreString];
}
secondViewController:
-(void)saveString:(NSString *)myString {
[[NSUserDefaults standardUserDefaults] setObject:myString forKey:@"totalScore"];
}
-(NSString *)retrieveString {
NSString *recoveredString = [[NSUserDefaults standardUserDefaults]objectForKey:@"firstScore"];
return recoveredString;
}
-(void) viewDidLoad {
NSString *firstScore = [self retrieveString];
NSInteger firstScoreInt = [firstScore intValue];
NSInteger newTotalScore = firstScoreInt+1;
NSString *newTotalScoreString = [NSString stringWithFormat:@"%i", newTotalScore];
[self saveString:newTotalScoreString];
}
I hope I have explained the problem understandable, so maybe someone can help me with this.
If I’m understanding this correctly, the error that u’r making here is that since addOne function in your firstViewController is also updating the total score, but you are not saving the total score there. So in your saveString function in the firstViewController, add this line too :
Hope this helps