Creating an abstract class in Objective-C

前端 未结 21 2495
感情败类
感情败类 2020-11-22 15:44

I\'m originally a Java programmer who now works with Objective-C. I\'d like to create an abstract class, but that doesn\'t appear to be possible in Objective-C. Is this poss

21条回答
  •  花落未央
    2020-11-22 16:30

    In fact, Objective-C doesn't have abstract classes, but you can use Protocols to achieve the same effect. Here is the sample:

    CustomProtocol.h

    #import 
    
    @protocol CustomProtocol 
    @required
    - (void)methodA;
    @optional
    - (void)methodB;
    @end
    

    TestProtocol.h

    #import 
    #import "CustomProtocol.h"
    
    @interface TestProtocol : NSObject 
    
    @end
    

    TestProtocol.m

    #import "TestProtocol.h"
    
    @implementation TestProtocol
    
    - (void)methodA
    {
      NSLog(@"methodA...");
    }
    
    - (void)methodB
    {
      NSLog(@"methodB...");
    }
    @end
    

提交回复
热议问题