Difference between id and NSObject

2019-04-26 19:11发布

问题:

In Objective-C, id<protocol> or NSObject<protocol> are frequently used for delegate declaration.

What are the main differences between id and NSObject? When do you want to use one versus the other?

回答1:

id<protocol> obj is the declaration for any object that conforms to the specified protocol. You can send any message from the given protocol to the object (or from the protocols that <protocol> inherits from).

NSObject<protocol> *obj is the declaration for any object that

  • conforms to the given protocol, and
  • is derived from NSObject.

That means that in the second case, you can send any methods from the NSObject class to the object, for example

id y = [obj copy];

which would give a compiler error in the first case.

The second declaration also implies that obj conforms to the NSObject protocol. But this makes no difference if <protocol> is derived from the NSObject protocol:

@protocol protocol <NSObject>