今天讲Objective-C的“Conforming to Protocols”话题。
Conforming to Protocols
The syntax to indicate that a class adopts a protocol again uses angle brackets, like this
@interface MyClass : NSObject <MyProtocol>
...
@endThis means that any instance of MyClass will respond not only to the methods declared specifically in the interface, but that MyClass also provides implementations for the required methods in MyProtocol. There’s no need to redeclare the protocol methods in the class interface—the adoption of the protocol is sufficient.
Note: The compiler does not automatically synthesize properties declared in adopted protocols.
If you need a class to adopt multiple protocols, you can specify them as a comma-separated list, like this:
@interface MyClass : NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol>
...
@end
One relatively common pitfall for new OS X and iOS developers is to use a single application delegate class to contain the majority of an application’s functionality (managing underlying data structures, serving the data to multiple user interface elements, as well as responding to gestures and other user interaction). As complexity increases, the class becomes more difficult to maintain.
Once you’ve indicated conformance to a protocol, the class must at least provide method implementations for each of the required protocol methods, as well as any optional methods you choose. The compiler will warn you if you fail to implement any of the required
methods.
Note: The method declaration in a protocol is just like any other declaration. The method name and argument types in the implementation must match the declaration in the protocol.
本文介绍Objective-C中如何通过角度括号语法让类遵循协议。遵循协议意味着类实例不仅响应特定接口声明的方法,还提供遵循协议所需的方法实现。文章强调了不需要在类接口中重新声明协议方法,并讨论了遵循多个协议的情况。
234

被折叠的 条评论
为什么被折叠?



