Object-C 协议

Protocols 协议

协议是一个组可以被任何类实现的方法和属性的集合,一些比类的接口更加灵活,他可以使您在完全无关的不同类之间共享一个接口声明。可以在现有类实现不同类之间的平行关系(注:这个是相对于继承关系而言)

Creating Protocols 创建协议

协议也是在.h文件中,可以通过Xcode的category创建协议。

Creating a protocol in Xcode 通过xcode 创建协议

In this module, we’ll be working with a protocol called StreetLegal. Enter this in the next window, and save it in the project root.

本章我们将创建一个叫StreetLegal的协议

这个协议我们将捕捉机动车的一些行为。定义这些行为之后,可以使用任何的类。而不是从同一个类中继承。一个简单的协议如下:

// StreetLegal.h
#import <Foundation/Foundation.h>

@protocol StreetLegal <NSObject>

- (void)signalStop;
- (void)signalLeftTurn;
- (void)signalRightTurn;

@end

任何采用此协议的类,要实现这个协议中的所有方法。在协议名之后的,表示此协议同时添加了NSObject的内容。也就是说一个类在遵守
StreetLegal协议的同时也要遵守NSObject协议。

Adopting Protocols 采用协议

在类名之后,添加三角括号,在其中放置协议的名字,表示这个类采用了这个协议。创建一个类Bicycle,将他的头一行修改成如下。当然在您使用协议之前您必须引入他。

// Bicycle.h
#import <Foundation/Foundation.h>
#import "StreetLegal.h"

@interface Bicycle : NSObject <StreetLegal>

- (void)startPedaling;
- (void)removeFrontWheel;
- (void)lockToStructure:(id)theStructure;

@end

采用协议就像您将StreetLegal.h中的方法添加到Bicycle.h中一样。采用多个协议可以使用逗号隔开,例

// Bicycle.m
#import "Bicycle.h"

@implementation Bicycle

- (void)signalStop {
    NSLog(@"Bending left arm downwards");
}
- (void)signalLeftTurn {
    NSLog(@"Extending left arm outwards");
}
- (void)signalRightTurn {
    NSLog(@"Bending left arm upwards");
}
- (void)startPedaling {
    NSLog(@"Here we go!");
}
- (void)removeFrontWheel {
    NSLog(@"Front wheel is off."
          "Should probably replace that before pedaling...");
}
- (void)lockToStructure:(id)theStructure {
    NSLog(@"Locked to structure. Don't forget the combination!");
}

@end

现在您在使用Bicycle类时,您可以调用协议定义的方法。就好像您在Bicycle.h文件中定义的signalStop, signalLeftTurn,signalRightTurn方法。其实是在协议中定义的。

// main.mBicycle.h:
#import <Foundation/Foundation.h>
#import "Bicycle.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Bicycle *bike = [[Bicycle alloc] init];
        [bike startPedaling];
        [bike signalLeftTurn];
        [bike signalStop];
        [bike lockToStructure:nil];
    }
    return 0;
}

Type Checking With Protocols 关于协议类型检查

和类一样,协议也可以当做类型检查。为了确保这类采用了一个协议,我们在声明变量的时候,在数据类型后面加上协议的名字,如下所示。

// main.m
#import <Foundation/Foundation.h>
#import "Bicycle.h"
#import "Car.h"
#import "StreetLegal.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        id <StreetLegal> mysteryVehicle = [[Car alloc] init];
        [mysteryVehicle signalLeftTurn];

        mysteryVehicle = [[Bicycle alloc] init];
        [mysteryVehicle signalLeftTurn];
    }
    return 0;
}

不管Car 和 Bicycle是否集成自同一个父类,因为他们都现实了StreetLegal协议,所以他们生成的对象都可以赋值给id 。

可以使用conformsToProtocol方法检测协议:这个方法在NSObject协议中定义。这个方法需要一个协议对象,我们可以通过@protocol()指令,如同@selector()可以获取方法对象。

if ([mysteryVehicle conformsToProtocol:@protocol(StreetLegal)]) {
    [mysteryVehicle signalStop];
    [mysteryVehicle signalLeftTurn];
    [mysteryVehicle signalRightTurn];
}

使用这种方式,就像说”要确保这个对象是由某些特定功能的”。对于动态类型,这是非常强大的工具,他可以使您定义一个非常好的API,而不用担心这个方法处理的到底是什么类型的对象。

Protocols In The Real World 现实中的协议

在IOS开发中有很多的例子,任何的应用个的入口application delegate对象,可以处理一个应用的生命周期中的大部分事件。他没有强制代理继承某个特定的类,而是需要实现下面的接口。

@interface YourAppDelegate : UIResponder <UIApplicationDelegate>

只要实现了UIApplicationDelegate协议的任何类,都可以作为application delegate。代理模式也是通过实现协议而不是通过继承。

Summary 总结

In this module, we added another organizational tool to our collection. Protocols are a way to abstract shared properties and methods into a dedicated file. This helps reduce redundant code and lets you dynamically check if an object supports an arbitrary set of functionality.

You’ll find many protocols throughout the Cocoa frameworks. A common use case is to let you alter the behavior of certain classes without the need to subclass them. For instance, the Table View, Outline View, and Collection View UI components all use a data source and delegate object to configure their internal behavior. The data source and delegate are defined as protocols, so you can implement the necessary methods in any object you want.

The next module introduces categories, which are a flexible option for modularizing classes and providing opt-in support for an API.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值