Is it ok to re-sort an array each time you need to access an element at a specific index?

I have a TableViewController that displays a list of elements CoreData relationship. In my cellForRowAtIndexPath:, I am getting a sortedArray from the set and then accessing the element at indexPath.row. Then in didSelectRowAtIndexPath:, I am doing the same thing.

Is this considered a bad practice? I see a theoretical danger in that if my sorting method returns a differently sorted array on a subsequent call, I could end up interacting with object B, even though the user clicked on the cell that showed object A. It shouldn't be possible for my sorting to return a differently sorted array, but I still feel that it is technically risky.

The only other way I know of to do this is to have my tableViewController keep it's own NSArray member, and when it first loads, populate the array by sorting the set. The only problem with this is that I would then have to separately maintain both the set and the array; modifying, inserting, or deleting objects from both anytime the user changes something. Is that considered the "correct" way to display CoreData elements in a table?


I would definitely go with option B. Even though you would be maintaining your model data, and the array in your controller, this should not be too difficult. adding / deleting items from the controller would require an update to the model. Not only do you get around your problem of risking data duplication, but you would see a big gain in performance as you aren't acquiring a newly sorted array each time you call for it.

Define "okay". It's likely not as efficient if you're sorting the same keys he same way every time. On the other hand, cycles are cheap; if you're not worried about performance and this is the clearest way, then go for it.

What you seem to be asking about "sorted the same way every time" is what's called a "stable sort". Ask yourself this: if the order of something other than the key(s) used, then why aren't you sorting by those too?

Need Your Help

Memory Error during frame animation in Android application

android memory animation memory-leaks

Hi im trying to set up a frame animation with a series of images as a background for my splash page in an android application at the moment there is no errors but when I run the application it quits

Convert array php To C#

c# php arrays

I am using a web service that gets some phone numbers in php as below :