-1

我试图在不依赖 indexPaths 的情况下检查 tableView 中的一行。这类似于我之前问过的一个问题,但这似乎应该比它更容易。

我有一个静态值数组,它是我的 tableView 的数据源,称之为 fullArray。选择行时,它的值放在另一个数组中 - 允许呼叫它PartialArray。在我使用 indexPaths 执行此操作之前,我会使用以下方法迭代 partialArray:

for(NSIndexPath * elem in [[SharedAppData sharedStore] selectedItemRows]) { 
    if ([indexPath compare:elem] == NSOrderedSame) { 
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
}

奇迹般有效。但是,现在我正在尝试使用部分数组中的值来执行此操作,但遇到了麻烦。

以下是我认为它应该在我的 sudo 代码中的 cellForRowAtIndexPath 方法中工作的方式:

对于 fullArray 中的每个字符串,如果它在 partialArray 中,则获取它的 indexPath 并检查它。

我开始拼凑的代码:

for(NSString *string in fullArray) {
    if (partialArray containsObject:string) {
//Need help here. Get the index of the string from full array
    fullArray indexOfObject:string];
//And check it.

        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
}

看起来它不应该那么难,但我无法绕过它。

4

1 回答 1

0

我不知道您为什么要放弃存储索引路径,但这是您的决定。此外,您可能希望使用 anNSMutableSet来存储检查的项目而不是数组。例如,更好的变量名将是,checkedItems而不是partialArray.

无论如何,如果您只需要遍历元素fullArray并获取每个元素的索引,则可以使用两种方法之一。一种方法是只使用一个普通的旧 C 循环,如for语句:

for (int i = 0, l = fullArray.count; i < l; ++i) {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
        continue;
    NSString *item = [fullArray objectAtIndex:i];
    cell.accessoryType = [partialArray containsObject:item]
        ? UITableViewCellAccessoryCheckmark
        : UITableViewCellAccessoryNone;
    }
}

另一种方法是使用enumerateObjectsWithBlock:方法:

[fullArray enumerateObjectsUsingBlock:^(id item, NSUInteger index, BOOL *stop) {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
        return;
    cell.accessoryType = [partialArray containsObject:item]
        ? UITableViewCellAccessoryCheckmark
        : UITableViewCellAccessoryNone;
}];
于 2012-11-12T20:03:20.897 回答