- (id)initWithManagedObjectContext:(NSManagedObjectContext *)moc
{
   if ((self = [super initWithStyle:UITableViewStylePlain])) {
      managedObjectContext = [moc retain];

      NSFetchRequest *request = [[NSFetchRequest alloc] init];
      [request setEntity:[NSEntityDescription entityForName:@"Person" 
                                     inManagedObjectContext:moc]];
      [request setSortDescriptors:[NSArray arrayWithObject:
         [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES]]];

      resultsController = [[NSFetchedResultsController alloc]
                            initWithFetchRequest:request
                            managedObjectContext:moc 
                              sectionNameKeyPath:nil 
                                       cacheName:nil];

      resultsController.delegate = self;

      [request release];

      NSError *error = nil;

      if (![resultsController performFetch:&error]) {
         NSLog(@"Bd podczas pobierania danych: %@", error);
      }
   }
   return self;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
   return [[resultsController sections] count];
}

- (NSInteger)tableView:(UITableView *)tableView
   numberOfRowsInSection:(NSInteger)section
{
   return [[[resultsController sections] objectAtIndex:section] numberOfObjects];
}

- (void)configureCell:(UITableViewCell *)cell 
   atIndexPath:(NSIndexPath *)indexPath
{
   NSManagedObject *person = [resultsController objectAtIndexPath:indexPath];

   cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", 
                                [person valueForKey:@"firstName"], 
                                [person valueForKey:@"lastName"]];
   cell.detailTextLabel.text = [NSString stringWithFormat:@"%i tasks", 
                                     [[person valueForKey:@"tasks"] count]];
}

- (UITableViewCell *)tableView:(UITableView *)tableView 
   cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier = @"PersonCell";

   UITableViewCell *cell = 
      [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

   if (cell == nil) {
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                     reuseIdentifier:CellIdentifier] autorelease];
      cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
   }
   [self configureCell:cell atIndexPath:indexPath];
  
   return cell;
}
