NSOrderedSet
Here’s a question: why isn’t NSOrderedSet a subclass of NSSet? It seems perfectly logical, after all, for NSOrderedSet–a class that enforces the same uniqueness constraint of NSSet–to be a subclass of NSSet. It has the same methods as NSSet, with the addition of some NSArray-style methods like objectAtIndex:.
NSOrderedSet is not a subclass of NSSet due to problems with Objective-C's single inheritance and the mutable/immutable class pairs in Foundation's class clusters.
It appears logical for NSOrderedSet to subclass NSSet, as it enforces uniqueness and shares methods. It would satisfy the Liskov substitution principle, allowing NSOrderedSet objects to replace NSSet ones without issues.
However, the method mutableCopy creates conflicts. NSSet's mutableCopy returns an NSMutableSet. If NSOrderedSet subclassed NSSet, its mutableCopy would return NSMutableOrderedSet, which is not a kind of NSMutableSet. This breaks code expecting NSMutableSet.
Making NSMutableOrderedSet subclass NSMutableSet fixes that, but then NSMutableOrderedSet is not a kind of NSOrderedSet, breaking other expectations.
You cannot stack mutable/immutable pairs without multiple inheritance, which Objective-C lacks. Protocols could help by defining behaviours like ordered or unique collections, but this would need changes to all APIs using NSArray or NSSet, causing pain and edge cases.
NSOrderedSet was added in iOS 5 and OS X Lion mainly for Core Data, to order relationships without custom attributes. It suits internal use or specific cases, but for API parameters, use NSArray (for order) or NSSet (for uniqueness). NSOrderedSet in parameters often adds needless complexity.
Category:
Tags:
Year: