Can a subclass overlap non-public methods

I have two classes: BatchDownloader , SpeechDownlader

BatchDownloader is a base class, and SpeechDownloader inherited it.

In BatchDownloader , whenever a single file is uploaded, -(void)downloadComplete:task called.

But in SpeechDownloader I also want to send a notification to downloadComplete:task .

Is it possible to simply write a method with the same name in the implementation of SpeechDownloader ? or is there a better way?

Thanks.

ps I do not want to publish -(void)downloadComplete:task public, because it must be called on its own.

+4
source share
2 answers

If you implement a method in a subclass that has the same name as the private method in the superclass, your subclass method will be called in instances of your subclass.

ie, if you implement a method in your superclass, for example, without declaring it somewhere:

 @implementation classA - (void)doSomething { NSLog("a"); } 

Then, in the implementation of your subclass, implement the method with the same name:

 @implementation subclassOfA - (void)doSomething { NSLog("b"); } 

When you call doSomething on an instance of your subclass, instead of implementing the superclass, you should call the implementation of the subclass , so the code in this example will cause b to print to the console.

However, if you also want to access the implementation of the method superclass, you can use:

 - (void)doSomething { [super doSomething]; NSLog("b"); } 

This will also invoke the implementation of the superclass. If you get a compilation error (because the private and super method did not appear to implement it), you can use [super performSelector:@selector(doSomething)] instead of doing the same.

This is because the call to Objective-C searches for methods. Since these methods have exactly the same method signature (same name, return type, and arguments [none]), they are considered equal, and the runtime always checks the class of the object before looking in superclasses, so it will find the implementation of the subclass method first .

In addition, this means that you can do this:

 classA *test = [subclassOfA new]; [test doSomething]; 

And, with surprise, the console will print " b " (or " ab " if you also called the super implementation).

+8
source

If you implement a method with the same method signature, it will be called the faith of your implementation, public or not.

+1
source

Source: https://habr.com/ru/post/1484359/


All Articles