2012-05-08 48 views
2

我想通過NSUserDefaults保存數據,並在tableView上查看它,但沒有發生後,我點擊保存按鈕,我停止後,再次運行應用程序我保存的數據它可以在每次覆蓋舊數據時看到它。難道我做錯了什麼?或者我應該使用與NSUserDefaults不同的東西?Xcode:保存與NSUserDefaults和TableView的數據問題

在此先感謝。

-(IBAction)save{ 

    NSUserDefaults *add1 = [NSUserDefaults standardUserDefaults]; 
    [add1 setObject:txt1.text forKey:@"txt1"]; 

    [add1 synchronize]; 
} 


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; 
    self.dataArray = [NSArray arrayWithObjects:[prefs objectForKey:@"txt1"], nil]; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [dataArray count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *string = [dataArray objectAtIndex:indexPath.row]; 

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if(cell==nil) 
{ 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
} 
    cell.textLabel.text=string; 

    return cell; 
} 

回答

2

你的代碼有兩個問題:

你不刷新tableview。您可以通過調用做到這一點:

[self.tableView reloadData]; // Or whatever property is pointing to your tableview 

每次保存的值,將其保存相同的密鑰(txt1)之下,這就是爲什麼你重寫每一次。如果你想要的項目列表(陣列)上的項目追加到該數組中,你可以做這樣的事情:

NSMutableArray *myList = [[[NSUserDefaults standardUserDefaults] valueForKey:@"myTxtList"] mutableCopy]; 
[myList addObject:txt1.text]; 
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithArray:myList] forKey:@"myTxtList"]; 
[add1 synchronize]; 
self.dataArray = myList; 
[self.tableView reloadData]; 

附:當然,你需要設置相應的dataArrayviewDidLoad

self.dataArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"myTxtList"]; 
1

我猜你需要在userDefaults保存數據之後調用[yourTableView reloadData]。這應該可以解決你的問題。

+0

謝謝你的回答。通常我的tableView指針叫做tbl1,我寫了[tbl1 reloadData];我得到reloadData沒有重新加載?請問你能幫幫我嗎 –

2

至於一種阿爾法說嘗試,除了&我有疑問,在你的save方法定義了。只要嘗試將其更改爲以下內容

-(IBAction)save:(id)sender{ 
    NSUserDefaults *add1 = [NSUserDefaults standardUserDefaults]; 
    [add1 setObject:txt1.text forKey:@"txt1"]; 

    [add1 synchronize]; 
    [tableView reloadData]; 
} 

這可能適用於您。