1
@protocol MyButtonViewDelegate <NSObject>
- (void)buttonView:(MyButtonView*)view buttonPressed:(UIButton*)button;
@end

i am new in objective-c, i am learning delegate according the book.

from the book, when we define protocol we just write like this @protocol MyButtonViewDelegate.

But what's the difference beteween @protocol MyButtonViewDelegate and @protocol MyButtonViewDelegate <NSObject>. Why we need <NSObject>?

Matt S.
  • 13,305
  • 15
  • 73
  • 129
BlackMamba
  • 10,054
  • 7
  • 44
  • 67
  • http://stackoverflow.com/questions/1588281/why-subclass-nsobject – Paddyd Sep 09 '13 at 15:12
  • @Paddyd The question you linked is quite different from this one. The linked question asks why (mostly) all objects are derived from NSObject, whereas this one asks why a protocol would adopt the NSObject protocol and whether that's necessary. – Caleb Sep 09 '13 at 16:02

1 Answers1

6

But what's the difference beteween @protocol MyButtonViewDelegate and @protocol MyButtonViewDelegate <NSObject>.

The <NSObject> says that the protocol MyButtonViewDelegate conforms to the NSObject protocol. That is, any object that conforms to the MyButtonViewDelegate protocol must also conform to the NSObject protocol. (You may not have realized it, but there's a protocol named NSObject as well as a class by that same name.) So, if you've got an object that conforms to MyButtonViewDelegate, it's safe to call methods like -hash, -isEqual:, -retain, -release, -isKindOfClass:, etc.

Every object you're likely to encounter will already conform to NSObject because the class NSObject conforms to protocol NSObject. The only other Objective-C base class that you might run into is NSProxy, and that also conforms to NSObject. Therefore, adding <NSObject> to your protocol probably won't make a real difference, but it's a nice way to make the requirement explicit.

Caleb
  • 124,013
  • 19
  • 183
  • 272
  • 1
    I got it. protocol `MyButtonViewDelegate` inherit protocol `NSObject`. I just think `NSObject` is a class, but i am wrong, it is also a protocol. – BlackMamba Sep 09 '13 at 15:20
  • @BlackMamba There's a class *and* a protocol named `NSObject`. The protocol declares a set of methods that every object, even those not derived from the `NSObject` class, is expected to implement. – Caleb Sep 09 '13 at 16:04