Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing a subclass to call its superclass method in Objective-C

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.

like image 403
Ideveloper Avatar asked Jan 09 '23 07:01

Ideveloper


1 Answers

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.

like image 87
KerrM Avatar answered Jan 19 '23 14:01

KerrM