Objective-C basics: protocol (@ protocol)

Source: Internet
Author: User

Objective-C basics: protocol (@ protocol)
C ++ Defines abstract interfaces with pure virtual functions. classes that inherit abstract interfaces must implement pure virtual functions of all parent classes. The protocols in OC are similar to pure virtual functions in C ++. 1. Declare the agreement. @ Protocol is followed by the protocol name. @ Protocol NSObject @ end if a protocol inherits from another protocol, fill in the parent protocol name in brackets as the declaration method. @ Protocol SonProtocol <BaseProtocol> @ end 2. The class conforms to a certain protocol. Fill in the protocol name with Angle brackets in the class declaration. @ Interface Car: NSObject <NSCopying> @ end @ interface Car: NSObject <NSCopying, NSCoding> @ end 3. the Protocol method declaration can use @ optional and @ require to indicate whether the classes that comply with the Protocol must implement the methods in the Protocol. @ Require is required, and @ optional is optional. Unlike C ++, C ++ must implement all pure virtual interfaces. @ Protocol WorkerProtocol <NSObject> @ optional-(void) doSomeOptionalWork; @ required-(void) doSomeRequiredWork; @ end the code above indicates that classes conforming to the WorkerProtocol must implement dosomerequired, doSomeOptionalWork is optional. 4. You can explicitly specify in the method parameters and instance variables that the object must comply with a certain protocol. @ Interface Manager: NSObject @ property (weak) id <WorkerProtocol> delegate;-(void) doWork; @ end the code above indicates that delegate must comply with the WorkerProtocol. If not, the compiler will warn. The following code will warn the compiler of Assigning to 'id <WorkerProtocol> 'from incompatible type 'nsstring * _ strong' NSString * name = @ "akon"; manager. delegate = name; [manager doWork];

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.