If you can target iOS 5.0 and above, then you could use an NSOrderedSet
to maintain the order of your objects. Please keep in mind that using this method is significantly less efficient than the other method I am suggesting below (as per Apple's documentation). For more information, please check the Core Data Release Notes for iOS 5.
If you need to support iOS versions before 5.0 or would like to use a much more efficient approach, then you should create an additional integer attribute in your entity and manually maintain the index of the entity's objects in it as they are being added or rearranged. When it's time to display the objects, you should sort them based on this new attribute and you're all set. For example, this is how your moveRowAtIndexPath
method should then look like:
- (void)moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath sortProperty:(NSString*)sortProperty
{
NSMutableArray *allFRCObjects = [[self.fetchedResultsController fetchedObjects] mutableCopy];
NSManagedObject *sourceObject = [self.fetchedResultsController objectAtIndexPath:sourceIndexPath];
// Remove the object we're moving from the array.
[allFRCObjects removeObject:sourceObject];
// Now re-insert it at the destination.
[allFRCObjects insertObject:sourceObject atIndex:[destinationIndexPath row]];
// Now update all the orderAttribute values for all objects
// (this could be much more optimized, but I left it like this for simplicity)
int i = 0;
for (NSManagedObject *mo in allFRCObjects)
{
// orderAttribute is the integer attribute where you store the order
[mo setValue:[NSNumber numberWithInt:i++] forKey:@"orderAttribute"];
}
}
Finally, if you find this too much manual work, then I really recommend using the free Sensible TableView framework. The framework will not only maintain the order automatically for you, it will also generate all the table view cells based on your entities' attributes and its relationships with other entities. Definitely a great time saver in my opinion. I also know of another library called UIOrderedTableView, but I've never used that myself so I can't recommend it (the former framework is also much more popular).