为什么在 NSUserDefault 中存储为 Object 的 Double 值不能反映在 UITableViewCell 中?



我试图在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];
        }
    }
}

您应该使用NSUserDefaultssetDouble:forKey:方法并让它为您管理该值。同时synchronizeNSUserDefaults为了保存值供以后使用

  • 设置用户默认值时没有使用doubleValue。要么这样做,要么像赫兹说的那样,使用setDouble方法。
  • 你没有在你的默认对象更新后调用synchronize
  • 不要释放empData,因为你没有保留它
  • 我假设userDefault是在其他地方设置的,当你使用它时,它不是nil ?

最新更新