I have two classes, Vehicle
and Car
; Car
is a subclass of Vehicle
.
There is a method logVehicleDetail
in the Vehicle
class.
Is there any way I can force Car
to call its superclass method logVehicleDetail
when overriding this method? If the subclass does not do that, then the complier should generate a warning or error.
For example, when compiling without ARC, the compiler warns if you don't call [super dealloc]
in your own dealloc
.
There are various ways of doing this. Perhaps the easiest and most straightforward way would be to add __attribute__((objc_requires_super))
to your method declaration:
@interface Vehicle : NSObject
-(void)logDetails __attribute__((objc_requires_super));
@end
@implementation Car
-(void) logDetails {
} // WARNING: Method possibly missing a [super logDetails] call
A different way to achieve a similar outcome would be to create a protocol for vehicles that log details e.g.
@protocol VehicleLogger <NSObject>
-(void)logDetails;
@end
in your Vehicle
header file. Then, in every subclass of Vehicle
that you want to log details, make it conform to that protocol.
@implementation Car <VehicleLogger>
That way, you will receive a warning in the compiler to implement that method. And in the implementation you can call super
's implementation of logDetails
:
-(void)logDetails {
[super logDetails];
//Do more stuff here, if I want
}
If on the other hand all you want is for every subclass to call Vehicle
's implementation, then simply don't implement that method in the subclass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With