Sorting Core Data objects by transformable attribute with NSFetchedResultsController
I'm displaying objects stored in Core Data in a UITableView and am having problems sorting these objects by one of the object's transformable attributes. I should point out that I'm using an NSFetchedResultsController as the controller between the Core Data store and my table view. When I was simply using an array to hold all of my objects, I could sort them without any problems 开发者_开发技巧at all. I'm using an FRC because I need the data grouped in sections with section headers and the FRC makes that very easy.
Let's call these objects I'm sorting "Measurement" objects. Each Measurement object has a distance attribute. That distance attribute is of a custom class, EPHDistance, so it's set up in the Core Data model as a Transformable attribute.
To make a long story short, the sorting of Measurement objects by their distance does work, but only after I've edited an object that's stored by Core Data or if I add a new object to the store. After editing the store and returning to my table that lists all the Measurement objects in order, everything works great. It's just the initial launch and viewing of the table view where the objects aren't sorted properly. I've actually placed an NSLog statement in my EPPDistance -compare: method and it's not getting called when I sort the objects until I add/edit an object in the Core Data store. For what it's worth, if I sort theses Measurement objects by their "date" attribute, which is an NSDate, it works great right out of the gate.
I'm not super experienced with Core Data and this is my first real attempt at using an NSFetchedResultsController so I'm a little baffled by this. Any input would be greatly appreciated.
Thanks a lot, Erik
You could create an optional method in your Measurement
class call -(NSString*)distanceCompareString
, which returns a string that will help you sort from your EPHDistance
object. The in your NSSortDescriptor, you just use distanceCompareString
as your sort key.
精彩评论