7. Agreement

Source: Internet
Author: User

Original: Http://rypress.com/tutorials/objective-c/protocols

Agreement

A protocol is a set of related properties and methods that can be implemented by any class. The protocol is more flexible than the interface of a generic class, and he can create a unified API definition between classes so that the same protocol can be abstracted by the same class if the same protocols are implemented.

Unrelated classes adopting the StreetLegal protocol

This chapter introduces knowledge of basic starvation protocols. We will also learn about the use of protocols in dynamic features.

Create an agreement

Just like the generic interface file for a class, the protocol is also defined in the. h file. Click Navigate to File > new> file ... or shortcut keys cmd+n, OS > Cocoa Touch Category Select Objective-c protocol to create the Protocol. "XF-XRH-XF: Different versions of Xcode will have different actions"

Creating a protocol in Xcode

In this chapter we will create a protocol called Streetlegal. In the dialog box, enter Streetlegal as the name to save it in the root directory of the project.

Our agreement will define some of the necessary vehicle behavior methods. The protocol allows these methods to take effect on the development object without using the integration class approach. An example of a simple Streetlegal is as follows:

// StreetLegal.h #import <Foundation/Foundation.h>@protocol streetlegal <nsobject>-(void ) Signalstop; -(void) Signalleftturn; -(void) Signalrightturn; @end

Any object that implements this protocol must implement all of the methods defined in the protocol. The <NSObject> expression behind the Protocol name NSObject Protocol (be careful not to NSObject mix with Class).

Interface implementation

If a class wants to implement an interface, the protocol can be wrapped up in an interface file with angle brackets after the class name. We're creating a new class called bicycle. It implements the Streetlegal protocol, which is described as follows:

// Bicycle.h #import <Foundation/Foundation.h>#import"StreetLegal.h"@ Interface bicycle:nsobject <streetlegal>-(void) startpedaling; -(void) removefrontwheel; -(void) Locktostructure: (ID) thestructure; @end

The implementation of the Protocol is like writing all the methods defined in the protocol to the class header file. Even if the bicycle class is a subclass of another class, the operation methods are the same. If you want to implement more than one protocol, the use is good (for example: <streetlegal, someotherprotocol>).

In the bicycle implementation file in fact and the general wording is no different, just need to implement the Protocol method are implemented in the implementation of the file can be:

//BICYCLE.M#import "Bicycle.h"@implementationBicycle- (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 bicycle the class, you can use the API (method) defined in the protocol.

// main.m #import <Foundation/Foundation.h>#import"Bicycle.h"int Main (intconstChar * argv[]) {    @autoreleasepool {        *bike = [[Bicycle alloc] init];        [Bike startpedaling];        [Bike Signalleftturn];        [Bike signalstop];        [Bike Locktostructure:nil];    }     return 0 ;}

Type Checking with Protocols

Like a class, a protocol can also be used as a variable type. Specific as follows:

//main.m#import<Foundation/Foundation.h>#import "Bicycle.h"#import "Car.h"#import "StreetLegal.h"intMainintargcConst Char*argv[]) {@autoreleasepool {ID<StreetLegal> mysteryvehicle =[[Car alloc] init];                [Mysteryvehicle Signalleftturn]; Mysteryvehicle=[[Bicycle alloc] init];    [Mysteryvehicle Signalleftturn]; }    return 0;}

Whether car and bicycle inherit from the same parent class, in fact they can use the ID <StreetLegal> variable to store as long as they all implement the same protocol. This example is to tell us this.

Use the Conformstoprotocol: method to check whether an object implements a protocol: This method is defined in the underlying protocol nsobject. We use @protocol()来讲协议协议名称作为参数传入, this very much like@selector(),只是@selector()将方法名称放入其中。就像这样:

if ([mysteryvehicle conformstoprotocol:@protocol(streetlegal)]) {    [mysteryvehicle signalstop];    [Mysteryvehicle Signalleftturn];    [Mysteryvehicle Signalrightturn];}

Using the protocol is like saying, "Confirm that there are some specific methods implemented in this object." Protocol is a very powerful dynamic programming technology, this can be your API more flexible, you do not have to worry about the use of the API to declare which class to parse.

Practice Agreement

In fact, you're already using a lot of protocols in your iOS and OSX app development process. such as "Application Delegate" object is one. The UIKit framework entry requires you to use this protocol:

@interface Yourappdelegate:uiresponder <UIApplicationDelegate>

Summarize

In this section, we've got a good tool. A protocol is a tool for the prime Minister's attributes and methods. Help you reduce redundant code. Enables you to dynamically invoke different objects that implement the same protocol.

You can find many examples of agreements in Cocoa frameworks. A simple usage scenario is not to subclass a class but also to change his behavior. For example, Table view, Outline view, and Collection Viewui parts all need to use the data source and delegate object to define the information and behavior. But data source and delegate are actually protocols, so you can define them anywhere and use them.

In the next section we will introduce classification, which is a kind of modular organization class and provides some clever usage.

7. Agreement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.