Sorted attribute

In order for me to have an entity in Core Data that I can use with an array, I need to have an index attribute for the entity that is used to remember the index of the array. The value of the index attribute would equal the index of the array. I also need an id attribute to uniquely identify the entity.
My problem comes when I add a new entry of the entity and then want to sort it alphabetically by the title attribute of the entity. How would I align the values of the index attribute with the new indices of the array? I need to do this because of the need to show the data represented by the entity in a picker view control in alphabetical order. Can anyone help?

@brower Thanks very much for your question!

I’m not sure I understand why you need to create an attribute that represents the index of the array. This seems unnecessary. I would imagine simply having a title attribute, and then sorting it alphabetically whenever you do a fetch request would suffice for you to have in your array. Because your collection in the array is not static, the indices will not remain constant, this is why having a specific attribute to mirror the index does not make sense. The issue here appears to be the order, and if they are sorted alphabetically, this would be enough to find the appropriate object in your collection. Because the collection is an array, you also have the count function to identify how many objects you have in the collection.

With your approach, you already have a collection of entities with an index attribute being held in an array, sorted in alphabetical order. As you pointed out, other entities could be added to the collection, not only will the collection have to be resorted based on the title attribute, but all the values of the index attribute in the collection would have to be reset AFTER they are sorted alphabetically, which would be a waste of time, and resources. Consider that this is going to be done each time an object is added, and also consider that if your collection begins to increase, then this could be a very wasteful operation.

Unless there is a very real need to maintain an index attribute, I would say avoid it altogether, especially since the objects are sorted alphabetically already, by the title attribute. Work with the title attribute, as well as the id attribute of each entity to correctly pinpoint the location of each object in your array, since this is what appears to be your main concern. :slight_smile:

Just as an afterthought, if you are planning to use your collection from Core Data to display in a UITableView, consider using NSFetchedResultsController as an alternative to hold your objects instead of an array. :slight_smile:

I hope this helps. All the best!

This topic was automatically closed after 166 days. New replies are no longer allowed.