What about class declaration and protocol declaration with the same name?

The NSObject class has the NSObject protocol.

What is the point?

Is this some way to emulate multiple inheritance?

What is the pattern?

+4
source share
2 answers

No. It's simple:

  • Foundation is too popular, and NSObject dominates the field when it comes to root classes.

  • That is why people are accustomed to his name and the messages and methods that he implements. For example, an Objective-C developer typically expects a class to implement + alloc and - init , but this is the only thing considered a general convention; the class does not necessarily do this.

  • But if NSObject not the root class of the hierarchy (for example, think about NSProxy , for example), it’s still convenient for it to respond to all NSObject messages, so you don’t need to learn a completely different, new set of names and conventions.

  • That's why Apple decided to extract these common methods into a separate protocol called NSObject , which implements the NSObject class - and any normal root class does.

Basically, it's just for convenience and code reading :)

+7
source

the main (practical / cosmetic) reason and something that you see in the MANY apple headings are other protocols.

Protocols

usually not inferred from NSObject .. this means that delegates and data sources that conform to a particular protocol no longer look NSObjects.

 @protocol TableDelegate ... @end id<TableDelegate> delegate = bla; 

==> The delegate does not respond to the basic NSObject methods. You will need to define it as NSObject ... but confusing the class and protocol in the definition is bad.

SO makes @protocol NSObject! And for this we need the NSObject protocol:

 @protocol TableDelegate<NSObject> ... @end id<TableDelegate> delegate = bla; 

===> delegate matches NSObject and everything feels more natural


it is also more akin to the idea of ​​"desiging to interface" imo

+3
source

Source: https://habr.com/ru/post/1485263/


All Articles