1

我正在使用 Apple 的MultiSelectTableView作为了解NSIndexSet. 我可以轻松地创建选定的项目并在调试器中读回它们。

当应用程序再次运行时,我尝试了几种方法来“读取”集合,但我无法弄清楚这一点。因此,如果我选择几行并退出应用程序,下次运行时,选择不会持续。我读过这篇文章,除其他外,但我只是不了解它。

我一直在尝试为此使用NSUserDefaults

NSMutableIndexSet *indicesOfItemsToShow = [NSMutableIndexSet new];

for (NSIndexPath *selectionIndex in selectedRows)
{
    [indicesOfItemsToShow addIndex:selectionIndex.row];
    NSLog(@"selectionIndex.row: %i", selectionIndex.row);
    NSUserDefaults *standardDefaults;
    [standardDefaults setObject:selectionIndex forKey:@"currentState"];
    [standardDefaults synchronize];
}

当我在视图加载时记录调试器时,索引为空。

4

2 回答 2

2

索引集不是用于表视图中的多行选择的正确工具,因为表视图数据由节和行表示,而索引集包含一维索引。

如果您希望保留多项选择,您可以使用-[UITableView indexPathsForSelectedRows]which 返回一个对象数组NSIndexPath。然后,您可以保留该数组,并在加载时读取该数组并使用它-[UITableView selectRowAtIndexPath:animated:scrollPosition:]来选择正确的单元格。

此外,您似乎错误地保存到用户默认值。

NSUserDefaults *standardDefaults;
[standardDefaults setObject:selectionIndex forKey:@"currentState"];

应该

NSUserDefaults *standardDefaults = [NSUserDefaults standardDefaults];
[standardDefaults setObject:selectionIndex forKey:@"currentState"];

一个警告。根据您在表视图中填充数据的方式,持久化选定行的索引可能是不安全的。跟踪选择了哪个支持对象并使用此信息来选择行会更好。但是对于静态数据,这是可以的。


为了进一步解释如何持久化选择,这里有一个例子:

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    NSArray* selectedRows = [tableView indexPathsForSelectedRows];
    NSMutableArray* safeForUserDefaults = [NSMutableArray new];

    [selectedRows enumerateObjectsUsingBlock:^(NSIndexPath* indexPath, NSUInteger idx, BOOL *stop)
    {
        NSDictionary* data = @{@"section": @(indexPath.section), @"row": @(indexPath.row)};
        [safeForUserDefaults addObject:data];
    }];

    [[NSUserDefaults standardDefaults] setObject:safeForUserDefaults forKey:@"currentState"];
}

现在,加载:

- (void)viewDidLoad
{
    NSArray* previousState = [[NSUserDefaults standardDefaults] objectForKey:@"currentState"];

    [previousState enumerateObjectsUsingBlock:^(NSDictionary* data, NSUInteger idx, BOOL *stop)
    {
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:[data[@"row"] integerValue] inSection:[data[@"section"] integerValue]] animated:NO scrollPosition:UITableViewScrollPositionNone];
    }];
}

这是一个非常简单的例子,但应该能让你上路。

于 2014-04-15T21:10:37.067 回答
1

就在您退出应用程序之前,将 self.storeIndexArray 添加到 NSUserDefaults

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

[self.storeIndexArray addObject:indexPath];

}

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

[self.storeIndexArray removeObject:indexPath];

}
于 2014-04-16T04:57:43.143 回答