Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-c: Calling [self message] on a base class is invoking the descendant method

I just started learning this, so sorry if this has some obvious solution I still can't grasp.

I have these two classes:

@implementation Person
-(void)saySomething:(NSString*) something {
    NSLog(@"%@",something);
}
-(void)yellSomething:(NSString*) something {
    [self saySomething:[something uppercaseString]];
}
@end

and

@implementation ShoutingPerson : Person

-(void)saySomething:(NSString*)something {
    [super yellSomething:something];
}

@end

This is causing a circular reference call because saySomething is always being called on the descendant class.

How can I make yellSomething invoke the saySomething method on Person class instead of the descendant class ?

like image 718
Niloct Avatar asked Dec 05 '22 13:12

Niloct


1 Answers

You don't. This is how inheritance is supposed to work in Objective-C. Instead, you should document in your base class that the default implementation of -yellSomething: just calls -saySomething:. It then becomes a subclass responsibility not to screw up the stack trace.

If you really want to be able to change what calls what, have a third method in your base class:

-vocalizeSomething: (NSString *)what loudly: (BOOL)loudly;

It's the one to speak the words. Both -saySomething: and -yellSomething: call through to it directly rather than calling each other. Then the subclass can safely override either method to call the other, or call vocalizeSomething:loudly: without creating an infinite loop.

like image 188
Jonathan Grynspan Avatar answered Feb 15 '23 23:02

Jonathan Grynspan