Search code examples
core-dataios5data-persistence

Save the state of a NSMutableArray with Core Data Entities as content


Scenario:

I am fetching different entity objects from my Core Data database and collecting them all into a single NSMutableArray. I have no problem massaging the data in the array and saving back to the Database. I need to save the state of the array between application launches.

Question: What is the best way to save a description of the entity objects in the array as well as the order they are in the array? (I have already tried saving the array to a dictionary, encoding the entity objects in to NSData. Didn't work because I couldn't decode the entity object.)

What is the best way to restore the array and fetch the entity objects from the database?

Thanks guys.


Solution

  • You have a couple different options. If the order of the objects in the "array" does not change too much, you can add an entity "MyFavoriteEntities" or some such, and give it a to-many ordered relationship to the entities you want to be included.

    Then, all you do is load that single MyFavoriteEntities object, and access all the other objects through that relationship.

    NOTE: Currently, ordered relationships are not supported on iCloud.

    The alternative (and in lots of situations, the preferred method) is to add an "ordering" attribute to your entities. Keep that updated with the order of your objects. Then, you can easily fetch the objects by giving a SortDescriptor for the "ordering" field. now, your objects will be fetched in the order you want.