(1) What is a protocol?
(2) how to define a protocol
(3) how to use the Protocol
(1) What is a protocol?
1. An interface object negotiated between multiple objects.
2. provides a series of methods for communication between Protocol Implementers and proxies.
3. Similar to pure virtual functions in c ++ or interfaces in java.
(2) how to define a protocol
1. Only header files
2. method definition
@ProtocolMyprotocol
-(Void) init;
-(Int) updata :( int) time;
@ End
3. Not every method in the Protocol must be implemented.
@ Required [Method must be implemented]
@ Optional [Methods can be implemented and default]
The Protocol must inherit from the basic protocol NSObject
Protocols can be inherited
@ProtocolMyprotocol
@ Optional
-(Void) init;
@ Required
-(Int)>
A simple Protocol example
Protocol example:
How do I know whether the shwoinfo method is written.
5. determine whether an object has a response method.
Dynamically determines whether a method is implemented.
If ([testRespondsToSelector: @ Selector (showInfo :)])
{
[Test> YES;
}
(3) how to use the Protocol
Create a protocol:
#import
@protocol Myprotocol
@optional- (void) printValue:(int)value;@required- (int) printValue:(int)value1 andValue:(int)Value2;@end
Methods for implementing the Protocol:
/// TestProtocol. h // TestPortocal // Created by ccy on 13-12-21. // Copyright (c) 2013 ccy. all rights reserved. // # import
# Import "Myprotocol. h" @ interface TestProtocol: NSObject
{}-(Void) testValue :( int) Value; @ end
/// TestProtocol. m // TestPortocal // Created by ccy on 13-12-21. // Copyright (c) 2013 ccy. all rights reserved. // # import "TestProtocol. h "@ implementation TestProtocol-(void) testValue :( int) Value {NSLog (@" testValue value: % d \ n ", Value);}-(int) printValue :( int) value1 andValue :( int) Value2 {NSLog (@ "printValue value1: % d, value2: % d \ n", value1, Value2); return 0;}-(void) printValue :( int) value {NSLog (@ "printValue % d \ n", value);} @ end
Call, use protocol:
//// Main. m // TestPortocal // Created by ccy on 13-12-21. // Copyright (c) 2013 ccy. all rights reserved. // # import
# Import "TestProtocol. h "// # import" Myprotocol. h "int main (int argc, const char * argv []) {@ autoreleasepool {// insert code here... NSLog (@ "Hello, World! "); TestProtocol * testPtcl = [[TestProtocol alloc] init]; [testPtcl testValue: 2]; [testPtcl printValue: 30 andValue: 40]; // determine whether the method has implemented SEL sel = @ selector (printValue :); if ([testPtcl respondsToSelector: sel]) {[testPtcl printValue: 20];} [testPtcl release]; // implement the id using the Protocol
Myprotocol = [[TestProtocol alloc] init]; [myprotocol printValue: 103]; [myprotocol release];} return 0 ;}