Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data fetchedresultscontroller question : what is "sections" for?

I'm trying to get to know Core Data (I'm a noob at iPhone development) and in order to do this I'm trying to get an object from the fetchedresultscontroller and NSlog it's name (a property of the object). I tried to do it like this:

NSArray *ar = [NSArray arrayWithArray:[fetchedResultsController sections]];
Task *t = [ar objectAtIndex:0];
NSLog(@"%@", t.taskName);

However, the app crashed with this error: the app crashes with the error

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[_NSDefaultSectionInfo taskName]: unrecognized selector sent to instance 0x3d1f670'

I have since learned that you need to use the fetched objects property for this, but then what is sections for? Thanks for any help, sorry if this is a supremely stupid question. I've looked over the documentation but still don't understand.

like image 895
Jake Avatar asked May 11 '10 08:05

Jake


1 Answers

NSFetchedResultsController can group your objects into sections based on a key you specify. So, for example, if your entity had a category property, you could group your objects by category and display them under a heading for that category.

Every UITableView (and every NSFetchedResultsController) contains at least one section, so even if you're not using this functionality, you'll still have to deal with sections. If you check the documentation, you'll see that the objects in the sections property conform to the NSFetchedResultsSectionInfo protocol, which has the objects property that contains the objects in that section.

There are two ways to get an actual object out of a NSFetchedResultsController:

id <NSFetchedResultsSectionInfo> sectionInfo = [fetchedResultsController.sections objectAtIndex:0];
Task *task = [sectionInfo.objects objectAtIndex:0];

The other, much simpler, and preferred way is to use the objectAtIndexPath: method.

Task *task = [fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];

These two samples are equivalent. UIKit adds some methods to NSIndexPath to make working with table views and fetched results controllers easier. Also, notice that the UITableViewDataSource and UITableViewDelegate methods all provide you with NSIndexPath objects, so you can generally just pass these to objectAtIndexPath: to get the correct object for that cell.

Apple also provides a decent tutorial on using Core Data on iPhone. It will answer a lot of your questions. Unfortunately, it doesn't cover NSFetchedResultsController in depth.

like image 180
Alex Avatar answered Oct 30 '22 21:10

Alex