Derek Derek - 1 year ago 74
iOS Question

Can I access CoreData objects by index?

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( == 5){ = "Hilary"

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

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download