2011-10-23 29 views
1

我試圖存儲Double值在NSUserDefault但雖然我能夠存儲它(因爲我的NSLog值顯示真值),當我試圖重新加載UITableView時,其Cell值不會更新userdefault中的當前值。當我打電話給我的setUserDefaults方法從UIAlertView爲什麼不能在UITableViewCell中反映存儲爲NSUserDefault中Object的Double值?

爲什麼會有如此怪異的行爲發生的委託方法

這種怪異的行爲只發生?

這裏是我的代碼: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]; 
} 

委託方法進行如下:

-(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]; 
     } 
    } 
} 
+0

你能顯示cellForRowAtIndexPath代碼嗎? – zakishaheen

回答

5
  • 設置用戶的默認值時,您沒有使用doubleValue。要麼這樣做,要麼按照herz的說法,使用setDouble方法。
  • 你是不是叫你的默認synchronize更新它
  • 不要鬆開EMPDATA對象後,你沒有挽留它
  • 我假設userDefault設置在其他地方,這是不是nil當你正在使用它?
+0

我爲empData使用alloc init,所以我相信我保留empData。另外,我相信我已經正確設置了userDefaults並且沒有零值。但我會嘗試使用同步... – DShah

+0

你不應該被分配/初始化,對不起,沒有注意到代碼的一部分。你從數組中獲得實際的對象,這樣你就有內存泄漏。你不需要alloc/init或release。 – jrturton

+0

我試過使用同步但沒有成功。另外,如果我想將double值存儲在userDefault中作爲Object,是否有可能?因爲我將Double Value設置爲String,然後將其存儲爲用戶默認值? – DShah

6

您應該使用setDouble:forKey:方法NSUserDefaults並讓它爲您管理值。另外synchronizeNSUserDefaults爲了保存價值供以後使用。

相關問題