Search code examples
objective-ccastingnsmutablearray

Does Objective-C implicitly typecast NSMutableArrays to NSArrays when returned?


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;

Solution

  • NSMutableArray is a subclass of NSArray, so yes, you don't have to do the type cast. It's textbook subtype polymorphism.