分类: iOS平台
2015-03-27 17:02:52
1.Protocol
类似接口
里面的方法,不必要全部实现
@protocol ButtonDelegate <NSObject> 代表实现协议NSObject
//对协议进行提前声明,和@class一样
@protocol ButtonDelegate;
2.// Button.h
#import
@class Button;
@protocol ButtonDelegate <NSObject>
-(void)onClick:(Button *)bb;
@end
@interface Button : NSObject
//delegate 就是按钮监听器
@property (nonatomic,retain) id <ButtonDelegate>delegate;
-(void)click;
@end
// Button.m
#import "Button.h"
@implementation Button
-(void)dealloc{
[_delegate release];
[super dealloc];
}
-(void)click{
//如果_delegate实现了onClick:方法就返回true
if( [_delegate respondsToSelector:@selector(onClick:)] ){
//按钮被点击了,并且告诉监听器哪个按钮被点击了
[_delegate onClick:self];
}
}
@end
// ButtonLi.h
#import
//对协议进行提前声明,和@class一样
@protocol ButtonDelegate;
@interface ButtonLi : NSObject<ButtonDelegate>
@end
// ButtonLi.m
#import "ButtonLi.h"
#import "Button.h"
@implementation ButtonLi
-(void)onClick:(Button *)b{
NSLog(@"%@按钮被点击了",b);
}
@end
// main.m
#import
#import "Button.h"
#import "ButtonLi.h"
#import "ButtonA.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//初始化按钮
Button *bu = [[[Button alloc] init] autorelease];
//初始化按钮监听器
ButtonLi *bul = [[[ButtonLi alloc] init] autorelease];
//设施按钮的监听器
bu.delegate = bul;
//点击按钮
[bu click];
}
return 0;
}