9

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?

Boon
  • 40,656
  • 60
  • 209
  • 315
  • Helpful http://stackoverflow.com/questions/466777/whats-the-difference-between-declaring-a-variable-id-and-nsobject – Maulik Dec 13 '13 at 13:15
  • 2
    This is not a duplicate, because "`id` vs `NSObject *`" and "`id vs NSObject *"` are significantly different questions. Voting to reopen. – Martin R Dec 14 '13 at 14:00
  • Martin is right, it's not the same. – Boon Dec 14 '13 at 15:30

1 Answers1

10

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>
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks Martin. So id is the same functionally as NSObject if protocol is derived from ? – Boon Dec 13 '13 at 14:29
  • @Boon: No. *"This makes no difference"* applies only to the last part of the answer, that both `id obj` and `NSObject *obj` imply that the object conforms to the NSObject protocol. - Perhaps I should delete the last part from the answer, it makes it only more confusing. – Martin R Dec 13 '13 at 14:39