3

The method discussion for setValue:forKeyPath: in Apple's NSKeyValueCoding Protocol documentation starts with:

The default implementation of this method [...]

Now, this might just be me getting caught with semantics but:

  1. How can an Objective-C Protocol have a default implementation?
  2. Since NSObject doesn't appear to conform to this protocol, how would one be able to take advantage of this default implementation in their own NSObject subclasses?
  • A related post is http://stackoverflow.com/questions/19329309/whats-wrong-with-using-a-category-on-nsobject-to-provide-a-default-protocol-imp?rq=1 – John Henckel Apr 17 '14 at 13:28

1 Answers1

5

NSKeyValueCoding is an informal protocol, which means it's implemented as a category (in this case, on NSObject). The NSObject class provides the default implementation of the methods declared in the category.

jlehr
  • 15,557
  • 5
  • 43
  • 45
  • Interresting! This raises a whole bunch of questions: 1) If NSKeyValueCoding is indeed implemented as a category, documentation-wise, how do you know this category is on NSObject and not another class? *Just trying to see how I could have arrived to this conclusion myself* ; 2) Can you override a method which was not implemented on the super class but, instead, implemented in one of the super's categories? –  Oct 04 '13 at 19:57
  • 1
    @QwertyBob: You can take a look at the NSKeyValueCoding.h file which declares the "protocol" -- it in fact contains a category on `NSObject`, not a `@protocol` block. You can override a superclass's category method. That behaves just like any other method. What you should not do is use a category to try to "override" a method on the same class: http://stackoverflow.com/questions/7013090/objective-c-categories-and-inheritance – jscs Oct 04 '13 at 20:31
  • 2
    @QwertyBob To reinforce Josh Caswell's point, whenever I teach classes on Objective-C and iOS, I encourage students to develop the habit of Command-clicking symbols in Xcode to jump to their definition and look around a bit before checking the documentation. As any example, very different things jump out at you when you skim through NSKeyValueCoding.h vs. the formal docs, though each is highly informative in its own way. – jlehr Oct 04 '13 at 20:34
  • @QwertyBob: it also says "informal category" in the documentation – newacct Oct 05 '13 at 00:07