- (void)viewDidLoad
{
   [super viewDidLoad];

   UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
      initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
                           target:self 
                           action:@selector(addTask)];
   self.navigationItem.rightBarButtonItem = addButton;
   [addButton release];
}

- (void)configureCell:(UITableViewCell *)cell 
   atIndexPath:(NSIndexPath *)indexPath
{
   NSManagedObject *task = [resultsController objectAtIndexPath:indexPath];
   cell.textLabel.text = [task valueForKey:@"name"];

   if ([[task valueForKey:@"isDone"] boolValue]) {
      cell.accessoryType = UITableViewCellAccessoryCheckmark;
   } else {
      cell.accessoryType = UITableViewCellAccessoryNone;
   }
}

- (void)addTask
{
   NSManagedObject *task = [NSEntityDescription
      insertNewObjectForEntityForName:@"Task"
               inManagedObjectContext:[person managedObjectContext]];

   [task setValue:[NSString stringWithFormat:@"Zadanie %i", 
      [[person valueForKey:@"tasks"] count] + 1] forKey:@"name"];
   [task setValue:[NSNumber numberWithBool:NO] forKey:@"isDone"];
   [task setValue:person forKey:@"person"];

   NSError *error = nil;
   if (![[person managedObjectContext] save:&error]) { 
      NSLog(@"Wystąpił błąd %@, %@", error, [error userInfo]);
   } else {
   }
}

- (void)tableView:(UITableView *)tableView 
   didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   [tableView deselectRowAtIndexPath:indexPath animated:YES];
   NSManagedObject *task = [resultsController objectAtIndexPath:indexPath];
   if (![[task valueForKey:@"isDone"] boolValue]) {
      [task setValue:[NSNumber numberWithBool:YES] forKey:@"isDone"];

      NSError *error = nil;
      if (![[task managedObjectContext] save:&error]) {
         NSLog(@"Wystąpił błąd %@, %@", error, [error userInfo]);
         abort();
      }
      [self.tableView 
      reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
        withRowAnimation:UITableViewRowAnimationFade];
   }
}
