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

DSh*_*hah 1 iphone delegates objective-c nsuserdefaults uialertview

我试图存储DoubleNSUserDefault但是虽然我能够存储它(因为我的NSLog值显示真值),当我尝试重新加载UITableView时,其Cell值不会更新userdefault中的当前值.

这种奇怪的行为只有在我setUserDefaults从委托方法调用我的方法时才会发生UIAlertView

为什么会出现这种奇怪的行为?

这是我的代码:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

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];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Her*_*Rod 6

你应该使用setDouble:forKey:方法,NSUserDefaults让它为你管理价值.同样synchronizeNSUserDefaults,为了保存该值以备后用.


jrt*_*ton 5

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