Objective C - How can I create an interface?

前端 未结 4 528
别那么骄傲
别那么骄傲 2020-12-28 11:05

I need to be able to create an interface like you create in C# to enforce a group of classes to implement certain methods. Is this possible in objective c?

4条回答
  •  再見小時候
    2020-12-28 11:25

    In the Objective-C world, interfaces are called "Protocols"

    According to Apple,

    Protocols declare methods that can be implemented by any class. Protocols are useful in at least three situations:
    
    To declare methods that others are expected to implement
    To declare the interface to an object while concealing its class
    To capture similarities among classes that are not hierarchically related
    

    So, to declare a protocol you can:

    @protocol SomeClassProtocol
    - (void) do:(int) number something:(id) sender;
    - (void) somethingElse;
    @end
    

    To implement a protocol , you do:

    @interface MyClass : NSObject 
    @end
    

    Check out this link for the official documentation.

提交回复
热议问题