If I want to return an immutable array like this + (NSArray *)ids but inside this method I’m declaring a NSMutableArray because I want to sort it using -sortUsingSelector:.
Returning this method works perfect.
-
But is it “okay” to write code that declares that the return method should be one type and the actually type is another?
-
Does this work because
NSMutableArrayis a subclass ofNSArray? -
Is the actual return value an
NSArrayor anNSMutableArray?
Yes, it is provided the types are compatible; see the next paragraph. In fact, there are some cases in Cocoa (notably class clusters) that do that as well.
Exactly. Since
NSMutableArrayis a subclass ofNSArray, it inherits all its methods and declared properties, so it publicly behaves likeNSArray. This is called the Liskov substitution principle.The return value is whatever you’re returning. Since you’re returning an
NSMutableArray, it’s anNSMutableArray. From the caller perspective, it is an object that can be used like anNSArray.