协议与代理

作者:追风剑情 发布于:2019-2-26 10:55 分类:Objective-C

示例

GraphicObject.h

  1. // 协议 Drawing
  2. @protocol Drawing
  3.  
  4. //这里默认为@required
  5. -(void) paint;
  6.  
  7. //@optional指令后面定义的接口可选实现
  8. @optional //这个指令添加到了Objective-C 2.0中
  9. -(void) outline;
  10. //TODO:: 更多...
  11.  
  12. //@required指令后面定义的接口必须实现
  13. @required
  14. -(void) erase;
  15. //TODO:: 更多...
  16.  
  17. @end


Circle.h

  1. #import <Foundation/Foundation.h>
  2. #import "GraphicObject.h"
  3.  
  4. // 多个协议可以用逗号分开,例如 <protocolA, protocolB, ...>
  5. @interface Circle : NSObject <Drawing>
  6. -(void) paint;
  7. -(void) erase;
  8. @end


Circle.m

  1. #import "Circle.h"
  2.  
  3. @implementation Circle
  4.  
  5. -(void) paint
  6. {
  7. NSLog(@"paint");
  8. }
  9.  
  10. -(void) erase
  11. {
  12. NSLog(@"erase");
  13. }
  14.  
  15. @end


main.m

  1. #import <Foundation/Foundation.h>
  2. #import "Circle.h"
  3.  
  4. int main(int argc, const char * argv[]) {
  5. @autoreleasepool {
  6. Circle *c = [[Circle alloc] init];
  7. [c paint];
  8. [c erase];
  9. }
  10. return 0;
  11. }

运行测试

111.png

       非正式(informal)协议,实际上是一个分类,列出了一组方法但并没有实现它们。几乎每个人都继承相同的根对象,因此,非正式分类通常是为根类定义的。有时,非正式协议也称为抽象(abstract)协议。

如果查看头文件<NSScriptWhoseTests.h>,可能会发现如下一些方法声明:

  1. @interface NSObject (NSComparisonMethods)
  2. - (BOOL)isEqualTo:(nullable id)object;
  3. // Implemented using isEqual:. Returns NO if receiver is nil.
  4. - (BOOL)isLessThanOrEqualTo:(nullable id)object;
  5. // Implemented using compare. Returns NO if receiver is nil.
  6. - (BOOL)isLessThan:(nullable id)object;
  7. // Implemented using compare. Returns NO if receiver is nil.
  8. - (BOOL)isGreaterThanOrEqualTo:(nullable id)object;
  9. // Implemented using compare. Returns NO if receiver is nil.
  10. - (BOOL)isGreaterThan:(nullable id)object;
  11. // Implemented using compare. Returns NO if receiver is nil.
  12. - (BOOL)isNotEqualTo:(nullable id)object;
  13. // Implemented using compare. Returns NO if receiver is nil.
  14. - (BOOL)doesContain:(id)object;
  15. // Returns nil if receiver is not an NSArray or if array doesn't contain object.
  16. // This operator is not working against the database.
  17. - (BOOL)isLike:(NSString *)object;
  18. // argument should be a string using simple shell wildcards (* and ?).
  19. // (e.g. "Stev*" or "N?XT").
  20. // Returns NO if receiver is not an NSString.
  21. - (BOOL)isCaseInsensitiveLike:(NSString *)object;
  22. @end

这些代码为NSObject类定义了一个名为NSComparisonMethonds的分类。这项非正式协议列出了一组方法,可以将它们实现为协议的一部分。

标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号