2

I'm using CoreData as a persistent store for my app data but would like to access elements in my data model by index rather than iterating through the whole collection every time.

For example if I have data of the form:

  1. "George"
  2. "Bill"
  3. "George"
  4. "Barack"
  5. "Donald"

I'd like to be able to update the elements without searching the collection each time.

If the data was in an array this would be easy ie:

Presidents[5] = "Hilary"

There doesn't seem to be an easy way to do this in CoreData other than

for president in Presidents{
    if(president.id == 5){
        president.name = "Hilary"
     }
}

Which for large data sets will get hugely expensive. Am I missing something?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Derek
  • 2,092
  • 1
  • 24
  • 38

2 Answers2

2

Credit to @JohnElemans but he posted a comment rather than an answer so I'm posting this for others benefit.

Loading the objects from the Managed Object Context into an array (or dictionary) passes them by reference.

In the example above, assuming there is an object in presidents[5], it can be accessed in the conventional way.

presidents[5] = "Hilary"
Derek
  • 2,092
  • 1
  • 24
  • 38
0

If you are using CoreData you should retrieve data objects through fetching. This allows you to only load what is necessary. In this particular case, retrieving by CoreData's objectid has it's own method. Otherwise you would want to fetch using a predicate.

This link accomplishes what you are looking for (in swift): How can I get core data entity by it's objectID?

In Obj-c: How to get Core Data object from specific Object ID?

I'm unable to find information on the implementation but as table memory sizes are fixed I think it's likely the retrieval mechanism would be similar to an array, with the added overhead of accessing disk. You do not want to manually retrieve all objects and find the objectid yourself.

Community
  • 1
  • 1
bradkratky
  • 1,577
  • 1
  • 14
  • 28
  • Sorry I should have made clear, I'm providing the IDs myself and want to use that ID. – Derek Jul 05 '16 at 18:47
  • Oh I see. You should use the first part of my answer then. You fetch the objects, alter them and save. This may be helpful: http://jamesonquave.com/blog/core-data-in-swift-tutorial-part-2/. The section that's particularly relevant is halfway down, "We’ll create an NSPredicate that uses a string to represent the requirement that any object must fulfill in order to pass through the query". Your predicate would look like: let predicate = NSPredicate(format: "id == 5") – bradkratky Jul 05 '16 at 19:03