创建一个Protocol,相当于java的接口,但,有些方法不必实现,例如以下
#import <Foundation/Foundation.h>
@protocol MyProtocol
@optional
- (void) test1;
- (void) test2;
- (void) test3;
@required
- (void) test4;
@end
继承了该协议,并声明在@optional下的代码方法不是必须实现的,但@required下的方法必须实现。
例如以下Book类
#import <Foundation/Foundation.h>
#import "MyProtocol.h"
@interface Book : NSObject <MyProtocol>
@property (nonatomic,assign) int price;
@end
#import "Book.h"
@implementation Book
- (void) test4
{
}
- (void) dealloc
{
NSLog(@"Book is dealloc");
[super dealloc];
}
@end
创建一个模拟买票样例。仅仅要实现了该接口 就可以作为买票代理人
#import <Foundation/Foundation.h>
@protocol TicketAgentProtocol <NSObject>
- (int) getTicketCount;
- (int) getTicketPrice;
@end
#import <Foundation/Foundation.h>
#import "TicketAgentProtocol.h"
@interface Person : NSObject
@property (nonatomic,retain) id<TicketAgentProtocol> delegate;
- (NSString *) buyTicket;
@end
#import "Person.h"
@implementation Person
- (NSString *) buyTicket
{
return [NSString stringWithFormat:@"TICKET COUNT:%d ,TICKET PRICE:%d",
[_delegate getTicketCount],[_delegate getTicketPrice]];
}
-(void)dealloc
{
[_delegate release];
[super dealloc];
}
@end
创建一个符合条件的“代理人”,就可以实现买票业务。
#import <Foundation/Foundation.h>
#import "TicketAgentProtocol.h"
@interface Other : NSObject <TicketAgentProtocol>
@end
#import "Other.h"
@implementation Other
- (int) getTicketCount
{
return 1000;
}
- (int) getTicketPrice
{
return 100;
}
@end
#import <Foundation/Foundation.h>
#import "TicketAgentProtocol.h"
#import "Person.h"
#import "Other.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Person *p=[[[Person alloc] init] autorelease];
Other *other=[[[Other alloc] init] autorelease];
p.delegate=other;
NSLog(@"%@",[p buyTicket]);
}
return 0;
}