Capture default sorting in NSMutableArray?

87 views Asked by At

I have an NSMutableArray which contain objects retrieved from CloudKit. Initially, I'm not doing any sorting so it's using whatever sorting order the records are retrieved. There are some user interactions where I would then need to sort it for specific purposes. However, I want to be able to undo that sorting and go back to the default order. But since the initial sorting is not specified by me, I'm wondering if there is a way capture that initial sorting order? I looked at the documentation for NSMutableArray and NSSortDescriptor and didn't see any sort of methods that I could call to do that. Is there a built in way that I'm missing or does anyone have a custom way of doing this? Thanks!

1

There are 1 answers

3
imas145 On BEST ANSWER

AFAIK, NSArray (and therefore NSMutableArray) don't have any special default sorting. Their order is simply the order objects were added in the first place.

NSArray *arr1 = @[@1, @2, @3];
NSLog(@"%@", arr1); // (1, 2, 3)

NSArray *arr2 = @[@3, @1, @2];
NSLog(@"%@", arr2); // (3, 1, 2)

One solution to your problem is to store the initial array, and when the user wants to sort it, you copy the initial array, sort it and display it to the user, while keeping the original around. If the user wants to undo that, you just display the original array and get rid of the sorted copy.

Here is very basic pseudo-code:

NSMutableArray *originalArray = [self arrayFromCloudKit]; // fetch from CloudKit

// now the user wants it sorted alphabetically 
NSMutableArray *alphabeticallySorted = originalArray.mutableCopy
[alphabeticallySortedsortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
[self storeOriginalArray:originalArray];
[self displayUIWithArray:alphabeticallySorted];

// but if the user changes their mind, you just fetch the original and delete the sorted
NSMutableArray *originalArray = [self getOriginalArray];
[self displayUIWithArray:originalArray];