I’m trying to override a getter in Objective-C. I have two classes, First and Second, like:
First.h:
@interface First : MashapeResponse {
NSString* message;
}
@property(readwrite, retain) NSString* message;
@end
First.m:
#import "First.h"
@implementation First
@synthesize message;
@end
Second.h:
#import "First.h"
@interface Second : First
-(NSString*) message;
@end
Second.m:
#import "Second.h"
@implementation Second
-(NSString*) message {
return [NSString stringWithFormat:@"%@%@", @"Message is ", message];
}
@end
I’m trying to execute the following code, but it seems like the overridden method in Second is never executed.
First* first = [[First alloc] init];
[first setMessage:@"hello"];
NSLog(@"%@", [first message]); // "hello" expected
Second* second = (Second*) first;
NSLog(@"%@", [second message]); // "Message is hello" expected, but it's still "hello"
You’re actually casting a
Firstas aSecond(which is bad form); but the underlying type is stillFirst, that’s why you see the originalmessage(fromFirst). Alloc aSecond, and it should work as expected.