Reputation: 11700
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 NSMutableArray
is a subclass of NSArray
?
Is the actual return value an NSArray
or an NSMutableArray
?
Upvotes: 8
Views: 2599
Reputation: 3355
Whether it's "okay" or not is a difficult question. If it's a small project and only you use the code, it might be allright. However, if you rely on nothing being able to change the "NSArray
" returned, it's not ok. (See the last point)
Yes.
NSMutableArray
. A simple cast will let you change the values in it. If you actually want to a return an immutable object, do the following:
NSArray* immutableArray = [[mutableArray copy] autorelease];
return immutableArray;
Upvotes: 2
Reputation:
(…) is it "okay" to write code that declares that the return method should be one type and the actualy type is another?
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.
Does this work because NSMutableArray is a subclass of NSArray?
Exactly. Since NSMutableArray
is a subclass of NSArray
, it inherits all its methods and declared properties, so it publicly behaves like NSArray
. This is called the Liskov substitution principle.
Is the actual return value a NSArray or a NSMutableArray?
The return value is whatever you’re returning. Since you’re returning an NSMutableArray
, it’s an NSMutableArray
. From the caller perspective, it is an object that can be used like an NSArray
.
Upvotes: 6