我有一个基于标签的应用,并且每次在标签之间切换时都希望重新加载数据。所以我使用了viewWillAppear:
被调用,但数据没有重新加载。这可能是使用大量[NSUserDefault]
的结果吗?
这是我的代码:
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self reloadData];
}
-(void)reloadData {
//Loading all the data
totalApples = [[NSUserDefaults standardUserDefaults]integerForKey:@"totalApples"];
[self setText:[NSString stringWithFormat:@"%.01f", totalApples] withExistingAttributesInLabel:self.applesLabel];
applesPerSecond = [[NSUserDefaults standardUserDefaults]integerForKey:@"applesPerSecond"];
[self setText:[NSString stringWithFormat:@"%.01f", applesPerSecond] withExistingAttributesInLabel:self.applesPerSecondLabel];
applesPerClick = [[NSUserDefaults standardUserDefaults]integerForKey:@"applesPerClick"];
}
答案 0 :(得分:2)
使用NSUserDefaults
时,最好在写完数据后调用-synchronize
。
采用以下示例:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@100 forKey:@"SomeKey"];
[defaults synchronize]; //This will ensure data is written.
如果您不调用此方法,系统会定期执行此操作。但是,它可能会导致您可能遇到的时间问题。
详细了解NSUserDefaults
和此行为here。
<强>更新强>
我认为这个问题正在失去其背景。以下是您在评论中发布的更新方法。可能值得发布跟进问题,因为这可能不是NSUserDefaults
的问题。
至少后人是使用NSUserDefaults
写出数据的一个例子。我还更新了您的方法,以便将 priceFarmHands 保存为浮点数,因为正在执行乘法运算。 (它之前被写成整数,可能被截断)。
- (void)buyFarmhand {
farmHands++;
totalApples -= priceFarmHands;
if(priceFarmHands < 1000) {
priceFarmHands = priceFarmHands * 1.35;
} else if(priceFarmHands < 10000) {
priceFarmHands = priceFarmHands * 1.25;
} else {
priceFarmHands = priceFarmHands * 1.15;
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setFloat:priceFarmHands forKey:@"priceFarmHands"];
[defaults setInteger:farmHands forKey:@"farmHands"];
[defaults setDouble:totalApples forKey:@"totalApples"];
[defaults synchronize];
[self setText:[NSString stringWithFormat:@"%.f", priceFarmHands] withExistingAttributesInLabel:self priceFarmHandsLabel];
[self setText:[NSString stringWithFormat:@"%d", farmHands] withExistingAttributesInLabel:self.numberFarmhands];
}
答案 1 :(得分:0)
我没有看到你在哪里创建NSUserdefault对象,它应该在reloadData方法中创建,这应该可行:
-(void)reloadData {
//Loading all the data
NSUserDefaults *appleData = [NSUserDefaults standardUserDefaults];
totalApples = [appleData integerForKey:@"totalApples"];
applesPerSecond = [appleData integerForKey:@"applesPerSecond"];
applesPerClick = [integerForKey:@"applesPerClick"];
//Set the labels text
[self setText:[NSString stringWithFormat:@"%.01f", totalApples]
withExistingAttributesInLabel:self.applesLabel];
[self setText:[NSString stringWithFormat:@"%.01f", applesPerSecond]
withExistingAttributesInLabel:self.applesPerSecondLabel];
}
另外,为了帮助您解决此问题,请将一些日志添加到viewWillAppear
:
-(void)viewWillAppear:(BOOL)animated{
NSLog(@"viewWillAppear called, reloadind data...");
[super viewWillAppear:animated];
[self reloadData];
}