Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must Protocols Conform To The NSObject Protocol?

Tags:

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?

like image 291
CodaFi Avatar asked Apr 06 '12 21:04

CodaFi


People also ask

What is a Nsobject protocol?

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.

How do you conform to a protocol in Objective-C?

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.

How many protocols can a Swift class adopt?

Since classes, structures and, enums can conform to more than one protocol, they can take the default implementation of multiple protocols.

What is the difference between Swift protocol and Objective-C protocol?

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.


1 Answers

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.

like image 130
Rob Napier Avatar answered Oct 07 '22 20:10

Rob Napier