zoukankan      html  css  js  c++  java
  • Objective C 总结(六):协议

    协议是对象行为的抽象,定义了消息合约。Objective-C中可以实现多个协议

    @protocol XYZPieChartViewDataSource
    - (NSUInteger)numberOfSegments;
    - (CGFloat)sizeOfSegmentAtIndex:(NSUInteger)segmentIndex;
    @optional
    - (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex;
    - (BOOL)shouldExplodeSegmentAtIndex:(NSUInteger)segmentIndex;
    @required
    - (UIColor *)colorForSegmentAtIndex:(NSUInteger)segmentIndex;
    @end

    @optional的实现是可选的,@required的实现则是必须的。

    实现多协议

    @interface MyClass : NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol>
    ...
    @end

    id类型的协议约束

    由于id类型是范型,编译器无法在编译阶段对其类型进行检查,但提供了对其协议约束的语法

    id <XYZFrameworkUtility> utility = [frameworkObject anonymousUtility];

    这样,编译器就会检查utility是否实现了XYZFrameworkUtility协议。



  • 相关阅读:
    模板
    模板
    模板
    模板
    2017-2018 ACM-ICPC Asia Tsukuba Regional Contest
    牛客
    软件工程
    Codeforces Round 696(Div.2)
    Atcoder ARC111 contest
    Codeforces Educational Round 100(Div.2)
  • 原文地址:https://www.cnblogs.com/iprogrammer/p/3246056.html
Copyright © 2011-2022 走看看