Call subclass's method from its superclass - objective-c

I have two classes, named Parent and Child, as below. Parent is the superclass of Child I can call a method of the superclass from its subclass by using the keyword super. Is it possible to call a method of subclass from its superclass?
Child.h
#import <Foundation/Foundation.h>
#import "Parent.h"
#interface Child : Parent {
}
- (void) methodOfChild;
#end
Child.m
#import "Child.h"
#implementation Child
- (void) methodOfChild {
NSLog(#"I'm child");
}
#end
Parent.h:
#import <Foundation/Foundation.h>
#interface Parent : NSObject {
}
- (void) methodOfParent;
#end
Parent.m:
#import "Parent.h"
#implementation Parent
- (void) methodOfParent {
//How to call Child's methodOfChild here?
}
#end
Import "Parent.h" in app delegate's .m file header.
App delegate's application:didFinishLaunchingWithOptions: method..
Parent *parent = [ [Parent alloc] init];
[parent methodOfParent];
[parent release];

You can, as Objective C method dispatch is all dynamic. Just call it with [self methodOfChild], which will probably generate a compiler warning (which you can silence by casting self to id).
But, for the love of goodness, don't do it. Parents are supposed to provide for their children, not the children for their parents. A parent knowing about a sub-classes new methods is a huge design issue, creating a strong coupling the wrong way up the inheritance chain. If the parent needs it, why isn't it a method on the parent?

Technically you can do it. But I suggest you to alter your design. You can declare a protocol and make your child class adopt that protocol. Then you can have to check whether the child adopts that protocol from the super class and call the method from the super class.

You could use this:
Parent.m
#import "Parent.h"
#implementation Parent
- (void) methodOfChild {
// this should be override by child classes
NSAssert(NO, #"This is an abstract method and should be overridden");
}
#end
The parent knows about the child and child has a choice on how to implement the function.

super means "invoke a method dispatching on the parent class", so can use super in the subclass because a subclass only has one parent class. A class can have many _sub_classes though, so how would you know which method implementation to call, in the general case? (Hence there is no such thing as a sub keyword.)
However, in your example you have two separate methods. There's nothing stopping you (assuming you have very good reasons for doing something like this!) from saying, in the parent,
- (void) methodOfParent {
[self methodOfChild];
}

if your super has multiple subs then go for this one for the specific
sub's method
if ([super isKindOfClass:[specificsub class]]) {
[specificsub methodName];
}
if your super is dealing with that object (that sub) so sub's method
loggedin will be called an other way is in you super class
super *some = [[sub alloc] init];
[some methodName];

This can be done by over riding the method in subclass. That is create a method in parent class and over ride the same in subclass.

Related

Inheritance in class methods

I have the following class:
#interface ClassA
+ (void)method1;
+ (void)method2;
#end
#implementation ClassA
+ (void)method2 {
[self method1];
}
#end
And one that inherits from it:
#interface ClassB : ClassA
#end
#implementation ClassB
+ (void)method1 {
NSLog(#"ClassB");
}
#end
If in an specific segment of code I do:
[ClassB method2];
It will throw an error cause it will try to call [ClassA method1], but this class doesn't implement that method. Is it even possible somehow that call is make to ClassB and not to ClassA? Scenario is: I have a base class with some utility class methods that relate in between them. Children don't need to implement those, but need to implement one that is used inside some of those methods. But once the flow goes into the parent, when it calls this method, it calls the parent one - which is not implemented.
You have multiple problems:
First
First point deleted thanks to #rmaddy comments.
Second
Your methods return a instancetype variable, while they don't: if you want to leave your implementation like that, change your method to return void
Third
You forgot implementation of + (instancetype)method1; so this code it not valid.

Call a method in the class that created the current class?

This one's trickier to explain: I have ClassA which has MethodA, that does some stuff to some objects in ClassA, let's say it sets a couple of labels.
ClassA has also created an instance of ClassB, which is a sidebar view. I need ClassB to perform the same stuff to objects in ClassA as MethodA, updating those labels inside that instance of ClassA.
I need ClassB to be able to call MethodA, but have it act on the specific instance of ClassA that created that instance of ClassB.
The classes (at present at least) do not inherit from one another, since they don't actually share anything yet. I fill some data from ClassA into ClassB's labels, and now I need to do the opposite.
I can't call [super MethodA] from within ClassB, because they don't inherit. What I need is something analogous to a [parent methodA], which would call that method in the class that created this ClassB object, and have it act on that specific instance of ClassA.
Does such a thing exist? Apologies, jumbled post, and I'm not sure what to search for for a vague question like this.
No, if you are using composition then you need an external way to refer to the class the contains the client one.
The easier way to do it would be to pass the parent while instantiating the object:
#interface ClassB {
ClassA *parent;
}
-(id)initWithA:(ClassA*)parent;
#property (readonly, retain) ClassA *parent;
#end
#implementation ClassB
-(id)initWithA:(ClassA*)parent {
if ((self = [super init])) {
self.parent = parent;
}
return self;
}
#end
so that you can have in ClassB:
-(void)method {
[parent updateThings:params];
}
Mind that in this case, since both class declarations are cross referenced you will need a forward declaration (eg. #class ClassA) in header file to make it compile.
You need to create this yourself. The general pattern is to create a listener assignment in your child class, and the "parent" (more generically, the object wanting to receive notification) calls the method you establish to assign a listener. You can allow your child to maintain multiple listeners if you wish, or only a single listener. The listener should implement some protocol that is appropriate for how you plan to pass data.

Does super always reach to NSobject class in Objective-C?

the super keyword tells the compiler to search for method in the superclass of the class where the method is firstly defined. For example, if Class Father defines a new method called X which contains [super init], then I use method X in Class Son, the compiler would search for init method in Class Grandfather, since X is firstly defined in Class Father.
My question is, what if there exists a inherited method of NSObject that has not changed? For example, what if I use "init" method in a subclass that contains super? Since in this case, the init method is firstly defined in NSObject itself. Would it "skip over" NSObject, or just implements whatever inside NSObject since there is no higher classes?
-(id)init
{
self=[super init];
//code continues
}
What super means is that Objective-C calls the method on the self object, but does not use the implementation of the method in the same class as the one where super was called. Slightly confusing, but consider this:
#interface Grandparent : NSObject
- (void)a;
- (void)b;
#end
#implementation Grandparent
- (void)a {NSLog(#"Grandparent a");}
- (void)b {NSLog(#"Grandparent b");}
#end
#interface Parent : Grandparent
#end
#implementation Parent
- (void)a {NSLog(#"Parent a"); [super a];}
#end
#interface Offspring : Parent
- (void)a {NSLog(#"Offspring a"); [super a];}
- (void)b {NSLog(#"Offspring b"); [super b];}
#end
Look at the implementation of -[Offspring b]. It calls [super b], but Parent doesn't provide an implementation of -b. Objective-C will carry on looking up the hierarchy until it finds -[Grandparent b], and executes that. If Grandparent didn't have the method it would look on NSObject.
Now consider calling -[Offspring a]. That logs a message, then calls [super a], which is the implementation on Parent. That message in turn calls [super a]—because it does it in a method defined on Parent, this will start looking for -[Grandparent a] (even though the instance is actually an Offspring object).
What all this means is that for any NSObject descendent, calling a message via super has the possibility of ending up at the NSObject implementation of the method. That's not the same as saying that super always reaches NSObject, because there are classes in Objective-C that don't derive from NSObject (such as NSProxy).
You're right. Let's say neither Father nor Grandfather override init, but Son does, using the implementation in your snippet. If you do [[aSon alloc] init], the call to [super init] would look for Grandfather's implementation of init, which wouldn't be found, and then it would get to NSObject's implementation, which would then be executed.

Calling 'self' within super class in Objective-C

Superclass is an NSOperation class which implements NSXMLParserDelegate - all it does is sending URL request and parsing XML data returned from a server. This class is being inherited by a subclass which also implements NSXMLParserDelegate. The parent's parser delegate is supposed to catch general error from the XML response before passing it on to child's parser delegate to do more specific parsing.
Within the superclass:
#implementation Super
#pragma mark NSOperation method
- (void) main {
id parentDelegate = [self getParserDelegate]; //?
id childDelegate = [self getParserDelegate]; //??
}
// I would like this to return parser delegate in the super class
- (id) getParserDelegate {
return self;
}
#end
Within subclass:
#implementation Sub
// main is not overidden in subclass
// and this should return parser delegate in the sub class
- (id) getParserDelegate {
return self;
}
#end
I'm instantiating the operation using the child's class i.e. Sub
Sub *theSub = [[Sub alloc] init];
[self.queue addOperation:theSub]; // Super's main method will be called
Within Super's main method I would like to have access to both parent and child's delegate but I found that 'self' always resolves to Sub, regardless whether 'self' is called within Sub or Super. Is it possible to call Super's getParserDelegate from within Super's main or is it just a bad design?
self is a pointer directly to the object. So it resolves to the same thing no matter where you inspect it along the inheritance chain. There is no such thing as a self pointer that would resolve directly to the superclass — that's the difference between the 'is a' school of extending object functionality and 'has a'.
Any messages issued to self will always be sent first to the most junior child class, then work their way up per the usual inheritance rules. As a result there's absolutely nothing you can provide to NSXMLParser that would cause delegate methods to go straight in to the super class.
I'd suggest that what you're describing with a common actor that implements most of the logic and a separate actor that does twiddly specifics is itself the delegate pattern. So what you probably want is to turn what you currently have as a parent into its own sovereign class and attach what you currently have as the child to it as a delegate. Just reuse the NSXMLParserDelegate protocol for that delegation relationship if it makes sense.
Super class never know about what its child's, and what they do.
//in Super.h
- (id) getParserDelegate;
//in Super.m
- (id) getParserDelegate {
return self;
}
//in Child.h
- (id) getParserDelegate;
//in Child.m
- (id) getParserDelegate {
return [super getParserDelegate];
}

Is calling super in a category the same as calling it in a subclass?

Does calling [super init] do the same thing in a category as a subclass? If not, what's the difference?
In order to understand this, it's probably important to understand the way an object is stored during runtime. There is a class object1, which holds all the method implementations, and separately, there is a structure with the storage for the instance's variables. All instances of a class share the one class object.
When you call a method on an instance, the compiler turns that into a call to objc_msgSend; the method implementation is looked up in the class object, and then run with the instance as an argument.
A reference to super takes effect at compile time, not run time. When you write [super someMethod], the compiler turns that into a call to objc_msgSendSuper instead of the usual objc_msgSend. This starts looking for the method implementation in the superclass's class object, rather than the instance's class object.2
A category simply adds methods to the class object; it has little or no relation to subclassing.
Given all that, if you refer to super inside of a category, it does indeed do the same thing that it would inside of a class -- the method implementation is looked up on the class object of the superclass, and then run with that instance as an argument.
Itai's post answers the question more directly, but in code:
#interface Sooper : NSObject {}
- (void) meth;
#end
#interface Sooper ()
- (void) catMeth;
#end
#interface Subb : Sooper {}
- (void) subbMeth;
#end
#interface Subb ()
- (void) catSubbMeth;
#end
#implementation Sooper
- (void) meth {
[super doIt]; // Looks up doIt in NSObject class object
}
- (void) catMeth {
[super doIt]; // Looks up doIt in NSObject class object
}
#end
#implementation Subb
- (void) subbMeth {
[super doIt]; // Looks up doIt in Sooper class object
}
- (void) catSubbMeth {
[super doIt]; // Looks up doIt in Sooper class object
}
#end
1 See Greg Parker's writeup [objc explain]: Classes and meta-classes
2One important thing to note is that the method doesn't get called on an instance of the superclass. This is where that separation of methods and data comes in. The method still gets called on the same instance in which [super someMethod] was written, i.e., an instance of the subclass, using that instance's data; it just uses the superclass's implementation of the method.
So a call to [super class] goes to the superclass object, finds the implementation of the method named class, and calls it on the instance, transforming it into the equivalent of [self theSuperclassImplementationOfTheMethodNamedClass]. Since all that method does is return the class of the instance on which it was called, you don't get the superclass's class, you get the class of self. Due to that, calling class is kind of a poor test of this phenomenon.
This whole answer completely ignores the message-passing/method call distinction. This is an important feature of ObjC, but I think that it would probably just muddy an already awkward explanation.
No, they do different things. Imagine a class structure like this: NSObject => MyObject => MySubclass, and say you have a category on MyObject called MyCategory.
Now, calling from MyCategory is akin to calling from MyObject, and therefore super points to NSObject, and calling [super init] invokes NSObject's -init method. However, calling from the subclass, super points to MyObject, so initializing using super invokes MyObject's -init method, which, unless it isn't overridden, behaves differently from NSObject's.
These two behaviors are different, so be careful when initializing using categories; categories are not subclasses, but rather additions to the current class.
Given the below example, super will call UIView init (not UINavigationBar init method)
#implementation UINavigationBar (ShadowBar)
- (void)drawRect:(CGRect)rect {
//draw the shadow ui nav bar
[super init];
}
#end
If you subclass it, [super init] will call UINavigationBar init method.
So yes, if there are additional things you will do in UINavigationBar init (extra from UIView) they do different things.
Edit: the following is built on a flawed premise, please look at josh's answer.
not deleting, still an interesting reference for something that could potentially lead you astray.
They are the same thing... without referencing any outside dicussions we may have had where you stated that I should ..."answer an academic question with an academic answer"
#implementation categoryTestViewController (ShadowBar)
- (void)viewDidAppear:(BOOL)animated {
//draw the shadow ui nav bar
NSLog(#"super's class = %#, self's class %#",[super class],[self class]);
if ([self class] == [super class]) {
NSLog(#"yeah they are the same");
}
}
#end
outputs:
2011-05-29 08:06:16.198 categoryTest[9833:207] super's class = categoryTestViewController, self's class categoryTestViewController
2011-05-29 08:06:16.201 categoryTest[9833:207] yeah they are the same
and calling the [super viewDidAppear:] will result in calling nothing... not a loop, so I don't know what it is really doing there.