The NSObject protocol comes with the stock protocol templates, but it doesn't appear to be all that necessary for actual implementations of the protocol. Leaving it out seems to change absolutely nothing. So, is it really necessary for a protocol to inherit from it, or is it just an unnecessary add-on?
This protocol is imported into Swift with the name NSObjectProtocol . An object that conforms to this protocol can be considered a first-class object. Such an object can be asked about its: Class, and the place of its class in the inheritance hierarchy.
Objective-C uses angle brackets to indicate conformance to a protocol. This example declares a weak property for a generic object pointer that conforms to the XYZPieChartViewDataSource protocol.
Since classes, structures and, enums can conform to more than one protocol, they can take the default implementation of multiple protocols.
In Objective-C, protocols are declared with the “@protocol” keyword. Below is an example of declaring a protocol containing one required method. In Swift, the syntax is a little different but the idea is the same. In Objective-C, you add the protocol name in angle brackets beside the class interface declaration.
For years I (and many like me) didn't make our protocols conform to <NSObject>
. It works fine. But it can often be annoying. The most common annoyance is that you can't use respondsToSelector:
without casting back to NSObject*
(which kind of defeats the whole point of a protocol). That didn't matter back in the ObjC1 days because there was no @optional
, so none of us worried about it (we didn't use protocols much at all in those days since without @optional
they weren't that useful). Then ObjC2 came along with the wonderful addition of optional methods and suddenly respondsToSelector:
mattered. It took a little while for the slower of us, but eventually we started to figure out that life was much simpler if you make your protocols conform to <NSObject>
. Blessedly this has now made its way into Xcode, making it easier for everyone to do things in the more convenient way.
But no, you don't have to do it. It doesn't matter in many cases. But there's not much reason not to do it, so I recommend it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With