// MyProtocal.h @protocal MyProtocal <NSObject> - (void)protocolDefaultFun(); @required // 默认值,要求实现,不实现会报警告 - (void)protocolRequiredFun(); @optional // 可选实现 - (void)protocolOptionalFun(); @end
// MulProtocal.h @protocal MulProtocal <NSObject> - (void)mulProtocolDefaultFun(); @end
// Person.h #import <Foundation/Foundation.h> @protocal MyProtocal; @protocal MulProtocal; // 或者 @protocal MyProtocal, MulProtocal; // 只要一个类准遵守了一个协议,就拥有协议中声明的所有方法 @interface Person : Object <MyProtocal, MulProtocal> @end
// Person.m
#import "Person.h"
#import "MyProtocal.h"
#import "MulProtocal.h"
@implementation Person <MyProtocal, MulProtocal>
- (void)protocolDefaultFun()
{
}
- (void)protocolRequiredFun()
{
}
- (void)protocolOptionalFun()
{
}
- (void)mulProtocolDefaultFun()
{
}
@end// main.m
#import <Foundation/Foundation.h>
#import "MyProtocal.h"
#import "Person.h"
int main()
{
// 声明一个遵守了MyProtocal的对象
NSObject<MyProtocal>* obj1 = [[Person alloc] init];
obj1 = nil;
id<MyProtocal> obj2 = [[Person alloc] init];
obj2 = nil;
//
return 0;
}
四 代理
// ticketDelegate.h @protocol ticketDelegate <NSObject> - (int) leftTicketsNumber; @end
// Agent.h
@protocol ticketDelegate;
@interface Agent : NSObject <ticketDelegate>
@end
// Agent.m
#import "Agent.h"
#import "ticketDelegate.h"
@implementation Agent
- (int) leftTicketsNumber
{
return 1;
}
@end// Person.h @class Agent; @class ticketDelegate; @interface Person : NSObject - (void)buyTicket; // 代理属性 @property (nonatomic, retain) id <ticketDelegate> delegate; @end
// Person.m
#import "Person.h"
#import "Agent.h"
@implementation Person
- (void)buyTicket
{
if ( _delegate & [_delegate leftTicketsNumber] > 0)
{
NSLog(@"buy ticket");
}
}
@end
// main.m
#import "Person.h"
#import "Agent"
int main()
{
@autopool{
Person* p = [[Person alloc]init];
Agent* a = [[Agent alloc] init];
p.delegate = a;
[p buyTicket];
}
return 0;
}
原文地址:http://blog.csdn.net/xufeng0991/article/details/43373843