简体   繁体   中英

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;

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

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 .

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];

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM