What is the equivalent of a C++ pure-virtual function in Objective-C?

前端 未结 2 1885
孤街浪徒
孤街浪徒 2021-02-08 13:06

Simple answer would be Protocol.

The another point is that it is said that all methods in ObjectC are virtual, so no need to say virtual in ObjC.

I find it hard

相关标签:
2条回答
  • 2021-02-08 13:20

    Methods on objects in Objective-C are not virtual functions, they are real functions.

    I beg to differ, methods in Obj-C aren't quite real like one would expect. They behave just like virtual functions in C++ do, except you cannot make a 'pure virtual' function in Objective-C.

    Cheers, Raxit

    0 讨论(0)
  • 2021-02-08 13:33

    Simple answer would be Protocol.

    Simple but wrong. A protocol is an interface specification. It's a collection of messages that an object must (ignoring the @optional keyword for now) respond to.

    The term "virtual function" has no direct counterpart in Objective-C. In Objective-C you don't call functions on objects, you send messages to them. The object itself then decides how to respond to the message, typically by looking up the message in its class object, finding the associated method and invoking it. Note that this all happens at run time, not compile time.

    The mapping between messages (or "selectors" to give them their technical term) and methods is built entirely from the @implementation. The method declarations in the @interface are only there to give the compiler the information it needs to warn you that you may have forgotten a method implementation. And it is only a warning because you can't tell until run time whether whether the object really does respond to the message or not. For example, somebody else could add a category to an existing class that provides implementations for missing methods, or a class could override forwardingTargetForSelector: to forward messages it doesn't respond to elsewhere.

    0 讨论(0)
提交回复
热议问题