What is the difference between using an unofficial protocol in NSObject or a protocol with additional methods?

I study some basics of informal protocols and real protocols. What confuses me is that Cocoa seems to be using a lot of unofficial protocols for NSObject. These informal protocols are categories in NSObject that declare methods but do not actually implement them.

As far as I understand, the only reason they use informal protocols (in other words, categories in NSObject that don't provide method implementations) is to provide auto-complete hints in Xcode.

One example is the -awakeFromNib method defined in NSNibLoading.h, which is an unofficial protocol for NSObject. The nib boot system checks at runtime if an object implements this method. If so, then it causes it.

But now imagine that there was no function called an unofficial protocol. An alternative that would have the same effect would be a real @protocol declaration that declares the optional -awakeFromNib method. NSObject will simply accept this protocol, and the compiler will happily provide autocomplete.

Can anyone point out the big difference between the two strategies? I don't see the point in unofficial protocols, but really would like to do that.

+5
source share
3 answers

Two huge differences:

  • Checking the type of compilation time. An explicit protocol with additional methods is much clearer about which methods you could implement. Both of them explicitly decorate a class with a protocol that also conforms to it, and Xcode can provide much more accurate code completion lists of what you could implement.

  • Keeps NSObjectuncluttered. When using unofficial old-style protocols, all methods that are optional usually have a default implementation added to NSObject.

Unofficial protocols in which a clear solution to a problem that no longer exists since the introduction of additional methods in protocols in Objective-C 2.0.

+7
source

, @optional . . - .

+3

, , , ,

TestViewController : UIViewController <MyAwesomeProtocol>

, , ( ) ( UIViewController), , XCode .

, . , , ( , ), .

+1
source

All Articles