Objective-C: Polymorphism in the case of NSMutableArray
I'm a beginner in Objective-C programming and as I was working through an example, I noticed something curious about polymorphism:
// I know the message should have been mutableCopy, but this is how I came to find
// this ... anomaly
NSMutableArray *arrayCopy = [self.array copy];
[arrayCopy replaceObjectAtIndex:0 withObject:[NSNumber numberWithInt:2]];
This code compiles, however it will crash the app with a message saying arrayCopy does not recognise the message replaceObjectAtIndex:withObject:.
My question is, why would this compile in the first place (and it doesn't generate a warning/issue on Analyse)? Given that NSMutableArray inherits from NSArray, how can the assignment of arrayCopy to开发者_开发问答 a returned NSArray be valid?
Thanks in advance.
The method signature for copy is
- (id)copy
This means it returns a pointer to an Objective-C object but otherwise doesn't provide any type information to the compiler.
This means that the compiler can't warn you about the types being wrong.
精彩评论