2014-04-01 28 views
-2

我想保存爲我的UITableView選定的行。所以,當用戶回到屏幕上時,它會顯示他們最後的選擇。保存選定的行爲UITableView

這是我試過的代碼,其中,我想會做的伎倆:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    self.lastIndexPathUsed = indexPath; 
    NSData *responseData = [NSKeyedArchiver archivedDataWithRootObject:indexPath]; 

    [[NSUserDefaults standardUserDefaults] setObject:responseData forKey:@"IndexPathData"]; 
    [[NSUserDefaults standardUserDefaults] synchronize]; 

    [tableView reloadData]; 

} 

然後在我viewDidLoad中

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    NSData *responseData = [[NSUserDefaults standardUserDefaults]objectForKey:@"IndexPathData"]; 

    NSIndexPath *index = [NSKeyedUnarchiver unarchiveObjectWithData:responseData]; 
    self.lastIndexPath = index; 


} 

然而,responseData還沒有索引路徑保存。它總是NULL。即使在didSelectRowAtIndexPath方法中。

任何人都知道更好的方法來做到這一點?

+0

在應用程序委託中添加一個可變陣列並添加對象在didiselectro中添加索引path.row的索引w ..當你回來時只顯示他們 –

+0

不確定你在問什麼? – brandonscript

+0

我真的不想使用appDelegate來存儲或保存任何值。感謝這個想法,我會嘗試使用可變數組。 – Tander

回答

1
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSUserDefaults *userdefaults      = [NSUserDefaults standardUserDefaults]; 
    [userdefaults setObject:[NSString stringWithFormat:@"%d",indexPath.row] forKey:@"lastIndexPathUsed"]; 

} 
在viewDidLoad方法

然後

-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.lastIndexPath = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastIndexPathUsed"]; 
} 
+0

解決了我的問題。謝謝。 – Tander

1

您可以將其保存爲兩個值,後來重建NSIndexPath:

保存indexPath.row和indexPath.section分別然後重新創建它:

[NSIndexPath indexPathForRow:inSection:] 
+0

Indexpath.colum不存在? – Tander

+0

reserected Indexpath.section – sleepwalkerfx

+0

一旦我想出來,這實際上是一個更好的解決方案。謝謝! – Tander