Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

ios - Add extra row to a UITableView managed by NSFetchedResultsController

I'm using a UITableViewController for a table in my app, and I've added an NSFetchedResultsController to provide the data to show in the table (setting self as it's delegate).

However I would like to add a unique cell as the last cell of the table, unrelated to the items produced by the NSFetchedResultsController's predicate, I want this cell to always be at the bottom of the table.

I've tried simply added 1 to these methods in the table view data source:

- (NSUInteger)numberOfSectionsInTableView:(UITableView *)sender
{
    return [[self.fetchedResultsController sections] count] + 1;
}
- (NSUInteger)tableView:(UITableView *)sender numberOfRowsInSection:(NSUInteger)section
{
    return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects] + 1;
}

And then catching the case where this extra row is being generated like so (the table only has 1 section):

- (UITableViewCell *)tableView:(UITableView *)sender
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == [self.fetchedResultsController.fetchedObjects count]) {
        //Generate the last cell in  table.
    } else {
        //Generate the rest of the cells like normal.
    }
    return nil; //To keep the compiler happy.
}

This checks to see if the index is the last cell and deals with it appropriately.

However I am still getting the following error at runtime:

*** Terminating app due to uncaught exception 'NSRangeException', 
reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

Any idea what's causing this? Or is there a better way of adding an extra row to a table view controlled by an NSFetchedResultsController?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The fetched results controller is pretty tightly tied to the tableview, if you implement all the datasource methods as indicated in the documentation (the updates and so on). It will get pretty messy and hacky.

Could your "extra row" be the footer view of the table instead? This will always be at the bottom. It wouldn't be too much work to make it look like a cell, though from the look of it you want it to look different to the other cells anyway.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...