将额外的部分添加到NSFetchedResultsController

我正在为我公司编写一个小型iPhone应用程序,每周为每位员工显示预订情况。 我正在使用核心数据获取给定星期的“预订”列表,并希望将它们显示在一周内每天的一个分节中的UITableView中。

问题在于我需要为每周的每一天显示7个部分(显示'没有预约'单元格,其中部分/日期没有预订)。

我有一个应用程序截图,因为它站在这里(对不起,不能发布图像,因为我是新来的StackOverlow)

目前,我正在通过使用“fetchResults”方法实现此目的,该方法将预订并将其组织到一系列可能的日期中:

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

}

我的问题是:是否有任何方式使用NSFetchedResultsController实现相同的结果? 不知何故,我需要得到NSFetchedResultsController有7个部分,一个星期的每一天,其中一些可能没有预订。

任何帮助非常感谢:)


所以,因为天气不是很好,所以我已经回答了自己的问题,并实施了我在向westsider回复中描述的“解决方法”。

这个想法是保存一个'映射'数组(只是一个简单的7槽int数组),它将tableview将要求的部分映射到底层fetchedresultscontroller部分。 每个数组插槽将具有适当的部分索引或'-1',其中没有底层部分(并且应该显示'无预订'单元格)。

所以,我的refetchResults方法变成:

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

映射按以下方法设置。 这在每次映射需要刷新时调用 - 例如,当我从fetchedresultscontroller获得已添加/删除/等项目的回调时。

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

这可能会稍微优化一下,但现在可以正常工作。 我怀疑它可能会受到格林尼治标准时间/ BST时钟变化的问题,这将需要修复......而不是时钟变化的问题是紧急的,呃苹果? ,P

之后,它只是响应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;
    }
}

任何意见或更好的写作方式都非常受欢迎:)


我没有用过这么多,但你可能会检查出NSFetchedResultsSectionInfo协议。 它可以像这样使用,显然:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
NSInteger numberOfRows = 0; 
if ([[fetchedResultsController sections] count] > 0)
    {
    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    numberOfRows = [sectionInfo numberOfObjects];
    }
return numberOfRows;
}

祝你好运。


我也有这个问题。 我写了一个NSFetchedResultsController的子类来解决这个问题:

https://github.com/timothyarmes/TAFetchedResultsController

蒂姆

链接地址: http://www.djcxy.com/p/6133.html

上一篇: Adding extra sections to a NSFetchedResultsController

下一篇: Using custom sections with NSFetchedResultsController?