Search code examples
objective-cloopsnsarraycontroller

Iterate through NSArrayController in specific order


I need to iterate through an NSArrayController in a coredata model by a specific order.

Lets say that my model has these columns:

animal (string)
name (string)
age (int)

and I would like to iterate trough the controller like this:

for (animal *a in myNsArrayController.arrangedObjects)
{
  // Rest of code
}

but I would need to do it ordered by animal age... how can i do that?

A search did not bring me to any usable results..


Solution

  • Try this, it builds off of AKV's answer but uses your code and contains the for loop. I think this should work!

    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
    NSArray *sortedArray = [myNsArrayController.arrangedObjects sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
    for (animal *a in sortedArray)
    {
      // Rest of code
    }