Objective-C protocol (Protocol)

Source: Internet
Author: User

The role of the Protocol is similar to the multi-inheritance of abstract base classes in C ++. Similar to the interface concept in Java.
The Protocol is a list of multiple class sharing methods,Methods listed in the Protocol are not implemented in this class, but are implemented by other classes.

If a class complies with a protocol, the class must implement all methods of the specific Protocol (except for optional methods ).

To define a protocol, you need to use the @ protocol command, followed by the protocol name, and then you can declare some methods. The declaration of all methods before the command @ end is part of the Protocol. As follows:

@protocol NSCopying-(id) copyWithZone:(NSZone*) zone;@end

If your class decides to comply with the nscopying protocol, you must implement the copywithzone method. By listing the protocol name in a pair of angle brackets in @ interface, you are told to compile a protocol, for example:
@ Interface Test: nsobject <nscopying>

Instance:
Fly. h

#import <Foundation/Foundation.h>@protocol Fly  -(void) go;  -(void) stop;@optional  -(void)sleep;@end

Flytest. h

#import <Foundation/Foundation.h>#import "Fly.h"@interface FlyTest:NSObject<Fly> {}@end

Flytest. m

#import "FlyTest.h"@implementation FlyTest-(void) go {   NSLog(@"go");}-(void) stop {   NSLog(@"stop");}@end

Test. m

#import <Foundation/Foundation.h>#import "FlyTest.h"int main( int argc, char* argv[]){  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];  FlyTest *flytest = [[FlyTest alloc]init];  [flytest go];  [flytest stop];  [flytest release];  [pool drain];  return 0;}

The program running result is as follows:

Go
Stop


@ Protocol:
@ Protocol name <other protocols,...>
Method Declaration 1
@ Optional
Method Declaration 2
@ Required
Method 3
...
@ End

@ Optional indicates that the classes of the Protocol do not have to be implemented.
@ Required is a required method.



Related Article

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.