Surely an ordered set is a more-specific case of a set, so why does NSOrderedSet inherit from NSObject rather than NSSet?
Surely an ordered set is a more-specific case of a set, so why does
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I went through the interface of
NSSetand you’re right, ordered sets appear to satisfy the Liskov substitution principle and could therefor inherit fromNSSet.There is one little method that breaks this:
mutableCopy. The return value ofmutableCopymust be anNSMutableSet, butNSMutableOrderedSetshould inherit fromNSOrderedSet. You can’t have both.Let me explain with some code. First, let’s look at the correct behaviour of
NSSetandNSMutableSet:Now, let’s pretend
NSOrderedSetinherits fromNSSet, andNSMutableOrderedSetinherits fromNSOrderedSet:What if
NSMutableOrderedSetinherited fromNSMutableSetinstead? Then we get a different problem:In Example 1, you wouldn’t be able to pass an
NSOrderedSetinto a function expecting anNSSetbecause the behaviour is different. Basically, it’s a backwards compatibility problem.In Example 2, you can’t pass an
NSMutableOrderedSetinto a function expecting anNSOrderedSetbecause the former doesn’t inherit from the latter.All of this is because
NSMutableOrderedSetcan’t inherit from bothNSMutableSetandNSOrderedSetbecause Objective-C doesn’t have multiple inheritance. The way to get around this is to make protocols forNSMutableSetandNSOrderedSet, because thenNSMutableOrderedSetcan implement both protocols. I guess the Apple developers just though it was simpler without the extra protocols.