检查tableView中的一行

时间:2012-11-12 19:49:36

标签: ios uitableview

我正在尝试在不依赖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;
    }
}

似乎不应该这么难,但我无法绕过它。

1 个答案:

答案 0 :(得分:0)

我不知道为什么你会放弃存储索引路径,但那是你的电话。此外,您可能希望使用NSMutableSet来存储已检查的项目而不是数组。例如,更好的变量名称是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;
}];