How to create a protocol with methods that are optional?

前端 未结 5 1600
青春惊慌失措
青春惊慌失措 2020-12-12 17:02

I noticed methods marked optional in several protocols defined in the iPhone SDK, such as the UIActionSheetDelegate protocol for example.

How can I defi

5条回答
  •  一个人的身影
    2020-12-12 17:15

    Protocols act the same as abstract classes, so the @optional keyword defines those methods that are optional for implementation.

    So, in the code, someMethod1, someMethod2 and someMethod4 are required methods (must be implemented). someMethod3 is optional - if we didn't implement this method, the compiler will not throw any warnings.

    @protocol myPrtocol
    
    -(void)someMethod1:(id)someArgument;
    -(void)someMethod2:(id)someArugument;
    
    @optional
    
    -(void)someMethod3:(id)someArgument;
    
    @required //by default
    
    -(void)someMethod4:(id)someArgument;
    
    @end
    
    // sampleClass.m
    @interface sampleClass : someSuperClass 
    //...
    @end
    

提交回复
热议问题