@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
調用ui
#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; }