JSA986
JSA986

Reputation: 5936

Count number of rows that contain a string in table view always returns 1

My app dynamically adds table view rows that receive a pass/fail result displayed as the cell string (in addition to a description). Im trying to count the amount of cells that receive a fail result in the text. My problem is that my NSLog(@"Counted times: %i", times); always returns 1 rather than adding them up.

 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);

    }

UPDATED CODE

- (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;
 }

Upvotes: 0

Views: 158

Answers (2)

rmaddy
rmaddy

Reputation: 318854

You have:

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

Why would you expect this to ever return anything other than 1?

If you want to count the number of rows that meet some criteria, you need to loop through your data (not the cells), and check each value in your data.

Upvotes: 1

David Karasek
David Karasek

Reputation: 348

It looks like you are initializing the counter inside the loop, which constantly resets it. Declare the variable before the loop, then simply iterate it inside the loop.

Upvotes: 2

Related Questions