首先,确保您了解“实体”和“实例”之间的区别(并正确使用术语)。在与他人交流您的问题/解决方案方面,这一切都不同。
第二:不要担心 NSCollectionViewItems ......担心每个人的“代表对象”,它保存在某个容器中。
第三:您是否希望显示顺序成为实体的持久属性,还是只需要知道该项目目前处于什么位置,而不管以后可能是什么?重要的问题。
第四:Core Data 没有给你有序集合的概念。这是为了支持存储类型,例如 NSSQLiteStoreType,您可能只想在几个项目(或一个)中出错而不加载整个列表。因此,如果您想要一个持久的排序顺序,您只能靠自己。为此,只需向您的实体添加一个名为“sortOrder”的属性并将其设为数字类型。
第五:由于上述“无有序集合”问题,您尝试从一个数组中查找给定实体实例的索引,该数组是从一个集合构建的,该数组以不确定的顺序出现故障,注定会失败。
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)
关于我的第六点:如果您的应用程序的目标是 10.7 及更高版本,[NSManagedObject 现在为您提供有序关系。][1] 使用 -mutableOrderedSetValueForKey: 和 -mutableOrderedSetValueForKey: 设置和检索 NSOrderedSets。耶!