带有+ UITableView + 2个额外行的NSFetchedResultCintroller

时间:2011-03-12 00:44:34

标签: xcode uitableview nsfetchedresultscontroller rows

我正在尝试向我的UITableView添加两行。数据来自带有节的FetchResultsController。我已经尝试了通常与Array一起使用的技巧,但是他们没有使用FetchResultsController和section。简单地在numberofrows中添加+2也无济于事。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
     return ([[fetchedResultsController sections] count]+2);
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    return ([sectionInfo numberOfObjects]+2);
}

和fetchresultcontroller:

- (NSFetchedResultsController *)fetchedResultsController {
    // Set up the fetched results controller if needed.

    if (fetchedResultsController != nil) {
        return fetchedResultsController;
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"eventsEntity" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];


    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"eventName" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [request setSortDescriptors:sortDescriptors]; 
    [sortDescriptors release]; 
    [sortDescriptor release];

    NSFetchedResultsController *fetchedResultsController1 =
    [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                        managedObjectContext:managedObjectContext
                                          sectionNameKeyPath:@"eventName" cacheName:nil];


    self.fetchedResultsController = fetchedResultsController1;
    fetchedResultsController.delegate = self;

    [request release];
    [fetchedResultsController1 release];

    return fetchedResultsController;
} 

1 个答案:

答案 0 :(得分:2)

首先尝试获取不同概念:部分包含

因此,如果您想添加两个,您可以将它们添加到现有部分,或者添加另一部分并在该部分中添加两行。

这可能是最干净的解决方案,所以这是交易:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return ([[fetchedResultsController sections] count]+1); // +1 for your section
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSArray *sections = [fetchedResultsController sections];

    if ( section < [sections count] )
    {
        // the normal case, e.g. sections 0,1,2 of section.count==3
        id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:section];
        return [sectionInfo numberOfObjects];
    } else {
        // your own section, e.g. the 4th section, where the FRC returned 3 sections
        return 2;
    }
}

当然,在返回单元格,标题,行高等方法中需要进行类似的修改。