Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding extra sections to a NSFetchedResultsController

I'm writing a small iPhone app for my company that shows bookings for each employee one week at a time. I'm using core data to get a list of 'Bookings' for a given week and want to display them in a UITableView broken down in to one section per day of the week.

The problem comes in that I need to show 7 sections for each day of the week (showing a 'No Bookings' cell where a section/date has no bookings).

I've got a screenshot of the app as it stands here (sorry can't post images yet as I'm new to StackOverlow)

At the moment I'm achieving this by using a 'fetchResults' method which gets the bookings and organises them in to an array of possible dates:

- (void)refetchResults {    

// Drop bookings Array, replacing with new empty one
// 7 slots for 7 days each holding mutable array to recieve bookings where appropraite
self.bookings = [NSArray arrayWithObjects:[NSMutableArray array],
                  [NSMutableArray array], [NSMutableArray array],
                  [NSMutableArray array], [NSMutableArray array],
                  [NSMutableArray array], [NSMutableArray array], nil];

// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Booking" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

// Limit to this weeks data
[fetchRequest setPredicate:
 [NSPredicate predicateWithFormat:@"(date >= %@) && (date <= %@) && (resource == %@)",
  firstDate,lastDate,resourceId]];

// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"recId" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, sortDescriptor2, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

// Fetch records in to array
NSError *error;
NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (results == nil) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

[fetchRequest release];
[sortDescriptor release];
[sortDescriptor2 release];
[sortDescriptors release];

// Walk through records and place in bookings Array as required
for (Booking *item in results) {
    // Decide on array index by difference in firstDate and booking date
    int idx = (int)[[item date] timeIntervalSinceDate:firstDate]/86400;
    // Add the item to the approp MutArray
    [(NSMutableArray *)[bookings objectAtIndex:idx] addObject:item];
}

// Reload table
[tableView reloadData];

}

My question is: is there any way to achieve the same result using NSFetchedResultsController? Somehow I'd need to get the NSFetchedResultsController to have 7 sections, one for each day of the week, some of them possibly having no bookings.

Any help much appreciated :)

like image 748
Paul80nd Avatar asked Nov 01 '10 16:11

Paul80nd


1 Answers

So, being as the weather isn't very nice outside I've had a go at answering my own question and implementing the 'workaround' described in my reply to westsider.

The idea is to hold a 'mapping' array (just a simple 7 slot int array) which will map the section the tableview will ask for to the underlying fetchedresultscontroller section. Each array slot will have the appropriate section index or '-1' where there are no underlying sections (and where a 'No Booking' cell should be shown instead).

So, my refetchResults method becomes:

- (void)refetchResults {    

    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Booking" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    // Limit to this weeks data
    [fetchRequest setPredicate:
     [NSPredicate predicateWithFormat:@"(date >= %@) && (date <= %@) && (resource == %@)",
      firstDate,lastDate,resourceId]];

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
    NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"recId" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, sortDescriptor2, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];

    // Set up FRC
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"date" cacheName:nil];
    self.fetchedResultsController = aFetchedResultsController;
    self.fetchedResultsController.delegate = self;
    [aFetchedResultsController release];
    [fetchRequest release];
    [sortDescriptor release];
    [sortDescriptor2 release];
    [sortDescriptors release];

    // Run up FRC
    NSError *error = nil;
    if (![fetchedResultsController_ performFetch:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    // Update FRC map
    [self updateFRCMap];

    // Reload table
    [tableView reloadData];
}

The mapping is set in the following method. This is called whenever the mapping needs to be refreshed - for example when I get callbacks from the fetchedresultscontroller for items that have been added/deleted/etc.

- (void)updateFRCMap {

    // Set mapping table for seven days of week to appropriate section in frc
    for (int idx=0;idx<7;idx++) { frcMap[idx] = -1; }   // Reset mappings
    // For each section
    for (int sidx=0; sidx<[[self.fetchedResultsController sections] count]; sidx++) 
    {
        // If section has items
        if ([[[self.fetchedResultsController sections] objectAtIndex:sidx] numberOfObjects] > 0) 
        {
            // Look at first booking of section to get date
            NSDate *date = [(Booking *)[self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:sidx]] date];
            // Decide on array index by difference in firstDate and booking date
            int idx = (int)[date timeIntervalSinceDate:firstDate]/86400;
            // Set map
            frcMap[idx] = sidx;
        }
    }
}

This can probably be optimised a bit but works OK for now. I suspect it might suffer GMT/BST clock change problems which will need fixing ... not that clock change problems are all that urgent, eh Apple? ;P

After that it's just a case of using the mapping array when responding to the tableview:

#pragma mark -
#pragma mark Table view data source

// Gets the booking from the fetchedResultsController using a remapped indexPath
- (Booking *)bookingForMappedIndexPath:(NSIndexPath *)indexPath {
    return (Booking *)[self.fetchedResultsController objectAtIndexPath:
                       [NSIndexPath indexPathForRow:indexPath.row inSection:frcMap[indexPath.section]]];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 7;   // 7 days viewed
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Rows in section or 1 if no section
    if (frcMap[section] != -1) {
        id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:frcMap[section]];
        return [sectionInfo numberOfObjects];
    } else {
        return 1;
    }

}

- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"RegularCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {

    // If no actual bookings for section then its a blank cell
    if (frcMap[indexPath.section] == -1) {

        // Configure a blank cell.
        cell.textLabel.text = @"No Bookings";
        cell.detailTextLabel.text = @"";

        cell.textLabel.font = [UIFont systemFontOfSize:16];
        cell.textLabel.textColor = [UIColor lightGrayColor];

        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    } else {

        // Regular cell
        Booking *booking = [self bookingForMappedIndexPath:indexPath];
        cell.textLabel.text = booking.desc;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@", booking.location, booking.detail];

        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.textColor = [UIColor darkTextColor];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:12];

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }
}

Any comments or better ways of writing this are very much welcome :)

like image 128
Paul80nd Avatar answered Sep 30 '22 19:09

Paul80nd