I have 2 classes. Son
inherits from Dad
. (Note code has been simplified)
@interface Dad : NSObject
@interface Son : Dad
Dad Class
- (void)setupSession
{
dadSession = [NSURLSession config:config delegate:self delegateQueue:mainQueue];
// PROBLEM: self == Son, not Dad
}
Son class
- (void)startDadSession
{
[super setupSession];
}
then someone somewhere calls...
[son startDadSession];
I want the Dad class to be its own delegate for its session, but when I call [super setupSession]
from the Son
class, when the execution goes into the Dad class self == Son
.
Is there a way to have self
not be the instance of the Child class here?
Sadly, inheritance and delegates may sometimes interact in bad ways. Generally I find it hard to write code when a class inherits from another class that is a delegate. But it is necessary from time to time.
One solution I try is to override the delegate methods in the subclass and add a check for the correct instance ofNSURLSession
, or whichever is the correct object. If it is the wrong session, pass it on to the super class implementation. E.g.
- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error {
if (session == self.sonSession) {
// do stuff
} else {
// Unknown session, should be the dadSession so pass it on
[super URLSession:session didBecomeInvalidWithError:error];
}
}