开发者

Index of item within NSCollectionView

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 = [NSNu开发者_运维问答mber 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?


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.

Update for Lion (10.7)

With regard to my sixth point: If you're targeting 10.7 and above in your application, [NSManagedObject now gives you ordered relationships.][1] Use -mutableOrderedSetValueForKey: and -mutableOrderedSetValueForKey: to set and retrieve NSOrderedSets. Yay!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜