4 ms·
Protocols are "interfaces" (in the general sense of the word in programming). So they are useful when you want to write a delegate (or callbacks in the general
by hboon 15y ago
Protocols are "interfaces" (in the general sense of the word in programming). So they are useful when you want to write a delegate (or callbacks in the general sense of the word) class. Many classes have a delegate property that is of type id<SomeProtocol>. Equivalent to Java's interfaces, but Cocoa use protocols heavily for delegates only.
Categories are useful not for sharing code, but for expanding a class's functionality. This is especially useful when you write a class X that works with an existing class Y, but some of X's code should be an instance method of Y, or X introduces additional capability for Y to support X. UITableView adding functionality to NSIndexPath to support referencing table sections and rows is a good example. All those Java classes that add static methods to support existing Java classes, or if you used Smalltalk and added methods to existing classes, this is the equivalent.
- DrJokepu 15y ago(I agree with you, this is just nitpicking) >Equivalent to Java's interfaces, but Cocoa use protocols heavily for delegates only. Uh, NSCoding, NSCopying and the million other non-delegate protocols? Cocoa uses protocols heavily for a lot of things, not just delegates. The average Cocoa/Cocoa Touch developer, however, uses protocols mostly for delegates.