How to disable sorting for - allObjects in NSMutableSet?

48 Views Asked by At

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!

2

There are 2 best solutions below

0
On BEST ANSWER

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.

3
On

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

Then don't use a set, but an NSArray.
Arrays store their objects in an order, sets do not.