[Objective-C] Protocol 简介

本文深入探讨了Objective-C中的协议概念,解释了协议的作用、创建协议的方法、如何让类遵从协议以及如何通过类型检查来验证对象是否遵循特定协议。通过实际例子展示了如何在不同类间共享行为和功能,实现代码复用。
摘要由CSDN通过智能技术生成

转自:http://rypress.com/tutorials/objective-c/protocols


A protocol is a group of related properties and methods that can be implemented by any class. They are more flexible than a normal class interface, since they let you reuse a single API declaration in completely unrelated classes. This makes it possible to represent horizontal relationships on top of an existing class hierarchy.

【yasi】protocol 定义一组相关属性和方法,protocol自己不做实现。任意类都可以遵从同一个protocol,并实现其方法。这样可以使得,不相关的任何类都遵从同一套协议,在运行时具有灵活性。

Unrelated classes adopting the StreetLegal protocol

This is a relatively short module covering the basics behind working with protocols. We’ll also see how they fit into Objective-C’s dynamic typing system.

Creating Protocols

Like class interfaces, protocols typically reside in a .h file. To add a protocol to your Xcode project, navigate to File > New> File… or use the Cmd+N shortcut. Select Objective-C protocol under theiOS > Cocoa Touch category.


Creating a protocol in 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.

Our protocol will capture the necessary behaviors of a street-legal vehicle. Defining these characteristics in a protocol lets you apply them to arbitrary objects instead of forcing them to inherit from the same abstract superclass. A simple version of the StreetLegalprotocol might look something like the following:

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

@protocol StreetLegal <NSObject>

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

@end

Any objects that adopt this protocol are guaranteed to implement all of the above methods. The <NSObject> after the protocol name incorporates the NSObject protocol (not to be confused with theNSObject class) into the StreetLegal protocol. That is, any objects conforming to the StreetLegal protocol are required to conform to the NSObject protocol, too.

Adopting Protocols

The above API can be adopted by a class by adding it in angled brackets after the class/superclass name. Create a new classed calledBicycle and change its header to the following. Note that you need to import the protocol before you can use it.

【yasi】通过类似 @interface Bicycle: NSObject<StreatLega> 的方式就可以让 Bicyle 类遵从 StreetLegal 协议。遵从协议的类必须确保实现 protocol 中的所有 @required 方法,可以选择实现 @optional 方法

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

@interface Bicycle : NSObject <StreetLegal>

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

@end

Adopting the protocol is like adding all of the methods inStreetLegal.h to Bicycle.h. This would work the exact same way even if Bicycle inherited from a different superclass. Multiple protocols can be adopted by separating them with commas (e.g., <StreetLegal, SomeOtherProtocol>).

There’s nothing special about the Bicycle implementation—it just has to make sure all of the methods declared by Bicycle.h andStreetLegal.h are implemented:

// 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

Now, when you use the Bicycle class, you can assume it responds to the API defined by the protocol. It’s as though signalStop,signalLeftTurn, and signalRightTurn were declared in Bicycle.h:

【yasi】对遵从同一个protocol的多个类的对象,都可以调用protocol中任何方法

// main.m
#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

Just like classes, protocols can be used to type check variables. To make sure an object adopts a protocol, put the protocol name after the data type in the variable declaration, as shown below. The next code snippet also assumes that you have created a Car class that adopts the StreetLegal protocol:

// 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;
}

It doesn’t matter if Car and Bicycle inherit from the same superclass—the fact that they both adopt the StreetLegal protocol lets us store either of them in a variable declared with id <StreetLegal>. This is an example of how protocols can capture common functionality between unrelated classes.

Objects can also be checked against a protocol using theconformsToProtocol: method defined by the NSObject protocol. It takes a protocol object as an argument, which can be obtained via the @protocol() directive. This works much like the @selector()directive, but you pass the protocol name instead of a method name, like so:

【yasi】可以通过 conformsToProtocol 方法判断一个类的对象是否遵从某个 protocol,如果遵从,则对该对象执行protocol 中的方法

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

Using protocols in this manner is like saying, “Make sure this object has this particular set of functionality.” This is a very powerful tool for dynamic typing, as it lets you use a well-defined API without worrying about what kind of object you’re dealing with.

Protocols In The Real World

A more realistic use case can be seen in your everyday iOS and OS X application development. The entry point into any app is an “application delegate” object that handles the major events in a program’s life cycle. Instead of forcing the delegate to inherit from any particular superclass, the UIKit Framework just makes you adopt a protocol:

@interface YourAppDelegate : UIResponder <UIApplicationDelegate>

As long as it responds to the methods defined byUIApplicationDelegate, you can use any object as your application delegate. Implementing the delegate design pattern through protocols instead of subclassing gives developers much more leeway when it comes to organizing their applications.

You can see a concrete example of this in the Interface Builderchapter of Ry’s Cocoa Tutorial. It uses the project’s default app delegate to respond to user input.

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值