two way communication between class and superclass
[sorry for my weak english]
I have my common superclass S
for my five specific, but similiar, classes B1
,
B2
, B3
, B4
and B5
.
I want to put 'common' (similiar in each B's) code to S, (and call it by [super myCommonFunction]
).
It should be ok, but question is that myFunction need to call from inside one
specific function from B1
,B2
,B3
,B4
,B5
(it is the same type function with no arguments, even can have the same name in each),开发者_C百科
How to call self
methods from 'superclass'?
All you need to do is declare the method you want to call in your superclass, you can leave it's body empty or provide a default implementation if you want.
Then you simply provide further implementations in each subclass, overriding the superclass method.
Then when you need to call the method from the superclass you simply use [self myMethod]
and the correct subclass method will be called instead.
The approach suggested by @Tom is the one I would use if I'm certain that the methods in the descendant classes always have the same name. If the names can vary based on arbitrary conditions then here is another very flexible approach. You will want to change the method signatures to match your requirements:
typedef id (^common_function_callback_t)(void);
@interface S : ...
- (id) commonFunctionWithCallback:(common_function_callback_t) callback;
@end
@implementation S
- (id) commonFunctionWithCallback:(common_function_callback_t) callback
{
// ...
id someIntermediateResult = callback();
// ...
return someFinalResult;
}
@end
@implementation B1 // Similar for all other B's
- (id) myFunction
{
id someThing = ...;
id someStuff = [self commonFunctionWithCallback:^() {
return someThing;
}];
// ...
return someOtherResult;
}
@end
As I understood you want to call different method from S
class depending on which child class called your commonFunction
? If so - you can just check what is the instance of self
and do not call [super commonFunction]
, but [self commonFunction]
instead. This will automatically call [super commonFunction]
because self
inherits from super
.
精彩评论