Skip to content

Instantly share code, notes, and snippets.

@keicoder
Created February 22, 2014 09:08
Show Gist options
  • Select an option

  • Save keicoder/9150816 to your computer and use it in GitHub Desktop.

Select an option

Save keicoder/9150816 to your computer and use it in GitHub Desktop.
objective-c : count items
//count items and update table views lable
//loops through the ChecklistItem objects from the items array
//If the item object has its checked property set to NO, increment the local variable count by 1
//When looked at all the objects, return the value of this count to the caller
//Checklist.h
- (int)countUncheckedItems;
//Checklist.m
#import "ChecklistItem.h"
- (int)countUncheckedItems {
int count = 0;
for (ChecklistItem *item in self.items) {
if (!item.checked) {
count += 1;
}
}
return count;
}
//call method
//AllListsViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
Checklist *checklist = self.dataModel.lists[indexPath.row];
cell.textLabel.text = checklist.name;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d Remaining", [checklist countUncheckedItems]];
return cell;
}
//change to-do count and update label
//when user toggles a checkmark on an item, adds a new item or deletes an item
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.tableView reloadData];
}
//cellForRowAtIndexPath
int count = [checklist countUncheckedItems];
if ([checklist.items count] == 0) {
cell.detailTextLabel.text = @"(No Items)"; }
else if (count == 0) {
cell.detailTextLabel.text = @"All Done!"; }
else {
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d Remaining", count];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment