Implement a pure virtual method in Objective-C

前端 未结 6 1546
清酒与你
清酒与你 2020-12-02 18:22

I want to go to there. Seriously though, how does one implement a pure virtual method in an \"Apple\" way? Do you use a Protocol with your base class and throw exceptions on

6条回答
  •  醉话见心
    2020-12-02 19:02

    A virtual method is a method whose behavior can be overridden within an inheriting class by a function with the same signature (i.e same name with same number of params and type of params).

    Example:-

    @implementation BaseClass
    
    -(void)viewDidLoad
    {
     [self virtualMethod:123];
    }
    
    -(void)virtualMethod:(int)param
    {
     //implement this method in subclass
    }
    
    @end
    

    ////////////////////////////////////////////////////

    @interface ChildClass:BaseClass
    @end
    
    @implementation ChildClass
    
    -(void)virtualMethod:(int)param
    {
     NSLog(@"There is no keyword "Virtual" in Objective C.");
    }
    @end
    

    Output:-

    "There is no keyword "Virtual" in Objective C."

提交回复
热议问题