我的应用程序动态添加了表格视图行,这些行接收通过/失败结果显示为单元格字符串(除了说明)。我试图计算文本中接收失败的单元格的数量。我的问题是我的NSLog(@"Counted times: %i", times);总是返回1,而不是将它们加起来。

 cell.textLabel.text = [NSString stringWithFormat:@"Appliance %@:  %@", ((Circuit *)[self.circuits objectAtIndex:indexPath.row]).circuitReference,((Circuit *)[self.circuits objectAtIndex:indexPath.row]).rcdTestButton];
    if(cell.textLabel.text && [cell.textLabel.text rangeOfString:@"Fail"].location != NSNotFound){
        cell.textLabel.textColor = [UIColor redColor];

        NSString *string = @"str";
        int times = [[string componentsSeparatedByString:@"-"] count];

        NSLog(@"Counted times: %i", times);

    }


更新的代码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
   NSString *string = @"str";
   int times = [[string componentsSeparatedByString:@"str"] count];


static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (indexPath.section == 0) {
    cell.textLabel.text = @"Summary of appliance testing";
} else {
    //Appliance label text
    cell.textLabel.text = [NSString stringWithFormat:@"Appliance %@:  %@", ((Circuit *)[self.circuits objectAtIndex:indexPath.row]).circuitReference,((Circuit *)[self.circuits objectAtIndex:indexPath.row]).rcdTestButton];
    if(cell.textLabel.text && [cell.textLabel.text rangeOfString:@"Fail"].location != NSNotFound){
        cell.textLabel.textColor = [UIColor redColor];

        NSLog(@"Counted times: %i", times);

     }

        cell.imageView.image = [UIImage imageNamed:@""];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

return cell;
 }

最佳答案

你有:

NSString *string = @"str";
int times = [[string componentsSeparatedByString:@"-"] count];


您为什么期望它返回除1以外的任何值?

如果要计算满足某些条件的行数,则需要遍历数据(而不是单元格),并检查数据中的每个值。

07-24 09:36
查看更多