ios developer tiny share-20160930

本文介绍Objective-C中如何通过角度括号语法让类遵循协议。遵循协议意味着类实例不仅响应特定接口声明的方法,还提供遵循协议所需的方法实现。文章强调了不需要在类接口中重新声明协议方法,并讨论了遵循多个协议的情况。

今天讲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>
...
@end

This 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


Tip: If you find yourself adopting a large number of protocols in a class, it may be a sign that you need to refactor an overly-complex class by splitting the necessary behavior across multiple smaller classes, each with clearly-defined responsibilities.
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.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值