views:

37

answers:

1

In my collection view I need to generate an index for each item. As Items get reordered I need this index to update with its new position.

The data are Core Data entities in a managed NSArrayController. The closest I have come to a possible solution is implementing this method on the entity class and then using representedObject.dynamicIndex to bind it to the UI.

- (NSNumber *) dynamicIndex
{
    NSInteger r = [[[[self managedObjectContext] registeredObjects] allObjects] indexOfObject:self];
    NSNumber *result = [NSNumber numberWithInt:r];
    return result;
}

This solution is sketchy at best, and not really functional as it doesn't necessarily reflect the order in the collection view.

Anyone have a model / mechanism for generating or retrieving item indexes in an NSCollectionView?

+1  A: 

First, make sure you understand the difference between (and properly use the terminology of) "entity" and "instance." It makes all the difference in communicating your problems/solutions with others.

Second: Don't worry about NSCollectionViewItems ... worry about each one's "represented object," which is held in some container.

Third: Did you want the display order to be a persistent attribute of your entity or do you just need to know what position the item is in at the moment, regardless of what it might be later? Important question.

Fourth: Core Data does not give you the concept of ordered collections. This is to support store types such as NSSQLiteStoreType, where you might only want to fault in a few items (or one) without loading the whole list. Therefore, you're on your own if you want a persistent sort order. To do this, just add an attribute to your entity called "sortOrder" and make it a number type.

Fifth: Because of the "no ordered collections" issue above, your attempt to find the index of a given instance of your entity from an array, built from a set, which was faulted in with a nondeterministic order is doomed to failure.

Sixth: Since you're using an array controller, you'll need to set its sort descriptors. You'll want to use your "sortOrder" key. That way, your fetched instances will always be kept sorted by their "sortOrder."

Seventh and finally: If you're trying to get the index of any objects in your array controller's set/array of objects, you'll want to ask it for its -arrangedObjects, so you're getting the index of the object in the sorted collection the array controller controls.

Hope that helps.

Joshua Nozzi
Thanks for the info. This investigation has given me a clearer picture of what Core data is doing under the hood.I have since abandoned the collection view ui for a simplified outline view for this particular project.
Ryan Townshend