我试图在NSUserDefault
中存储Double
值,但是虽然我能够存储它(作为我的NSLog值显示真值),当我试图重新加载UITableView时,其单元格值未与userdefault中的当前值更新。
这个奇怪的行为只发生在我从UIAlertView
的委托方法调用我的 setUserDefaults
方法时
- (void)setUserDefaults
{
NSLog(@"setUserDefault : empArray: %d, empCount: %d",empArray.count, empCount);
NSMutableDictionary *empData = [[NSMutableDictionary alloc] init];
if (empArray.count>1)
empData = [empArray objectAtIndex:(empCount-1)]; // because empCount starts from 1. and empArray[0] = empCount 1
else
empData = [empArray objectAtIndex:0];
[userDefault setObject:[NSString stringWithFormat:@"%.2f",[empData objectForKey:@"salary"]] forKey:@"salary"];
NSLog(@"setUserDefaults: salary=%.2f",[[empData objectForKey:@"salary"] doubleValue]);
[empData release];
[self.tblView reloadData];
}
UIAlertView的委托方法如下:
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger) buttonIndex
{
if (alertView.tag == 1) // btnRemoveEmpPressed.
{
if(buttonIndex==0)
{
NSLog(@"buttonIndex 0");
}
else
{
NSLog(@"empRemovedPressed OK, buttonIndex 1, empArray Count %d, empCount %d",empArray.count, empCount);
// [empArray removeObjectAtIndex:(empCount)];
empCount -= 1;
lblTitle.text = [NSString stringWithFormat:@"Employee %d",empCount];
[self setUserDefaults];
}
// [tblView reloadData];
}
else if (alertView.tag == 2)
{
if (buttonIndex==1)
{
[self resetUserDefaults];
empCount = 1;
[empArray removeAllObjects];
lblTitle.text = [NSString stringWithFormat:@"Employee %d",empCount];
}
}
}
您应该使用NSUserDefaults
的setDouble:forKey:
方法并让它为您管理该值。同时synchronize
和NSUserDefaults
为了保存值供以后使用
- 设置用户默认值时没有使用
doubleValue
。要么这样做,要么像赫兹说的那样,使用setDouble
方法。 - 你没有在你的默认对象更新后调用
synchronize
- 不要释放empData,因为你没有保留它
- 我假设
userDefault
是在其他地方设置的,当你使用它时,它不是nil
?