Search code examples
macoscocoasortingnsmutableset

How to disable sorting for - allObjects in NSMutableSet?


In my OSX app I have NSMutableSet that contains custom objects. I implemented -isEqual and -hash methods in my custom object classes, so that the set can do comparison the way I want.

However, whenever I insert a new object into my set and then call -allObjects, the array that is returned has the objects in a sorted order.

The order depends on the value of the property that I'm using for comparison of my custom objects in -isEqual method mentioned above.

In my case, I want to preserve the order at which the objects were added to the set.

Does anyone have any clue how to achieve that?

Any kind of help is highly appreciated!


Solution

  • Sets don't have an order, they are specifically designed to be unordered collections. When you call allObjects to get an array, the order you get is not defined so you should not depend on it.

    You have 2 basic options here if you want to keep using sets.

    1. Order the array manually once you get it.

    2. Use an NSOrderedSet which maintains order.