协议与代理

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

示例

GraphicObject.h

// 协议 Drawing
@protocol Drawing

//这里默认为@required
-(void) paint;

//@optional指令后面定义的接口可选实现
@optional //这个指令添加到了Objective-C 2.0中
-(void) outline;
//TODO:: 更多...

//@required指令后面定义的接口必须实现
@required
-(void) erase;
//TODO:: 更多...

@end


Circle.h

#import <Foundation/Foundation.h>
#import "GraphicObject.h"

// 多个协议可以用逗号分开,例如 <protocolA, protocolB, ...>
@interface Circle : NSObject <Drawing>
-(void) paint;
-(void) erase;
@end


Circle.m

#import "Circle.h"

@implementation Circle

-(void) paint
{
    NSLog(@"paint");
}

-(void) erase
{
    NSLog(@"erase");
}

@end


main.m

#import <Foundation/Foundation.h>
#import "Circle.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Circle *c = [[Circle alloc] init];
        
        [c paint];
        [c erase];
    }
    return 0;
}

运行测试

111.png

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

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

@interface NSObject (NSComparisonMethods)
- (BOOL)isEqualTo:(nullable id)object;
    // Implemented using isEqual:. Returns NO if receiver is nil.
- (BOOL)isLessThanOrEqualTo:(nullable id)object;
    // Implemented using compare. Returns NO if receiver is nil.
- (BOOL)isLessThan:(nullable id)object;
    // Implemented using compare. Returns NO if receiver is nil.
- (BOOL)isGreaterThanOrEqualTo:(nullable id)object;
    // Implemented using compare. Returns NO if receiver is nil.
- (BOOL)isGreaterThan:(nullable id)object;
    // Implemented using compare. Returns NO if receiver is nil.
- (BOOL)isNotEqualTo:(nullable id)object;
    // Implemented using compare. Returns NO if receiver is nil.
- (BOOL)doesContain:(id)object;
    // Returns nil if receiver is not an NSArray or if array doesn't contain object.
    // This operator is not working against the database.
- (BOOL)isLike:(NSString *)object;
    // argument should be a string using simple shell wildcards (* and ?).
    // (e.g. "Stev*" or "N?XT").
    // Returns NO if receiver is not an NSString.
- (BOOL)isCaseInsensitiveLike:(NSString *)object;
@end

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

标签: Objective-C

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号