当我使用下面的代码时,我遇到的问题是 totalScore 仅在调用 secondViewController 中的 viewDidLoad 方法时才会更新。因此,如果我连续按两次 addOne 按钮,则两次检索字符串都是相同的,因此它只会将一个添加到相同的现有值,因为它尚未在 secondViewController 中更新。每次在 firstViewController 中按下 addOne 按钮时,我如何设法更新 secondViewController 中的 totalScore
第一视图控制器:
-(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];
}
第二个视图控制器:
-(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];
}
我希望我已经解释了可以理解的问题,所以也许有人可以帮助我。