Reputation: 11595
If I have a method like this:
-(NSArray *)methodThatReturnsAnArray;
And this is its implementation:
-(NSArray *)methodThatReturnsAnArray {
NSMutableArray *aMutableArray = [[NSMutableArray alloc] init];
[aMutableArray addObject:@"some string"];
return aMutableArray;
}
Will Objective-C implicitly cast aMutableArray
to NSArray
when it is returned, or do I have to specify that like this:
return (NSArray *)aMutableArray;
Upvotes: 1
Views: 398
Reputation: 52227
A cast doesn't change an object's type. It just tells the compiler it should assume it is a object of an certain type. But a (NSArray *)aMutableArray
will still be a NSMutableArray
.
Upvotes: 0
Reputation: 24125
NSMutableArray
is a subclass of NSArray
, so yes, you don't have to do the type cast. It's textbook subtype polymorphism.
Upvotes: 3
Reputation: 133567
As with inheritance in object oriented languages in general, since NSMutableArray
extends from NSArray
class it IS A NSArray
at all effect.
You don't need to cast it to a NSArray
because it is already a NSArray
, or in practice, it is able to respond to all messages to which an NSArray
could respond so it can be used in replacement to it.
Upvotes: 2
Reputation: 40211
You can simply return the NSMutableArray
object, since it's a subclass of NSArray
.
Note that it will still be a mutable array however. Usually this isn't a problem, but if you want to make sure it's non mutable, you have to create a new instance or a copy.
return [NSArray arrayWithArray:aMutableArray];
Upvotes: 0