@protocol Study;
int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *stu = [[[Student alloc] init] autorelease];
// 注意:OC是弱语法的,对类型要求不严格
// NSString *stu = [[[Student alloc] init] autorelease];
// [stu stringByAbbreviatingWithTildeInPath];
// conformsToProtocol:判断是否遵守了某个协议
if ([stu conformsToProtocol:@protocol(Study)]) {
NSLog(@"Student遵守了Study这个协议");
}
// respondsToSelector:判断是否实现了某个方法
if ( ![stu respondsToSelector:@selector(test)] ) {
NSLog(@"Student没有实现test这个方法");
}
}
return 0;
}
#import <Foundation/Foundation.h>
@protocol Study <NSObject>
// 默认就是@required
- (void)test3;
// @required表示必须实现的方法
// 虽然字面上说是必须实现,但是编译器并不强求某个类进行实现
@required
- (void)test;
- (void)test1;
// @optional表示可选(可实现也可不实现)
@optional
- (void)test2;
@end
#import <Foundation/Foundation.h>
@class Button;
// <>代表实现某个协议
@protocol ButtonDelegate <NSObject>
- (void)onClick:(Button *)btn;
@end
@interface Button : NSObject
// delegate就是按钮的监听器
@property (nonatomic, retain) id<ButtonDelegate> delegate;
// 点击按钮
- (void)click;
@end
#import "Button.h"
@implementation Button
- (void)dealloc {
[_delegate release];
[super dealloc];
}
- (void)click {
// 如果_delegate实现了onClick:这个方法
if ( [_delegate respondsToSelector:@selector(onClick:)] ) {
// 按钮被点击了,就应该通知监听器.并且告诉监听器哪个按钮被点击了
[_delegate onClick:self];
} else {
NSLog(@"监听器并没有实现onClick:方法");
}
}
@end
调用
#import <Foundation/Foundation.h>
#import "Button.h"
#import "ButtonListener.h"
#import "MyListener.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
// 初始化一个按钮
Button *button = [[[Button alloc] init] autorelease];
// 初始化一个按钮的监听器
// ButtonListener *listener = [[[ButtonListener alloc] init] autorelease];
MyListener *listener = [[[MyListener alloc] init] autorelease];
// 设置按钮的监听器
button.delegate = listener;
NSLog(@"button:%@", button);
// 点击按钮
[button click];
Button *button2 = [[[Button alloc] init] autorelease];
button2.delegate = listener;
NSLog(@"button2:%@", button2);
// 点击button2
[button2 click];
}
return 0;
}