oc的监听器使用方法(protocal)

mian.m
//
//  main.m
//  Protocal
//
//  Created by Rayln Guan on 8/29/13.
//  Copyright (c) 2013 Rayln Guan. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Button.h"
#import "ButtonListener.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        Button *btn = [[[Button alloc] init] autorelease];
        ButtonListener *btnl = [[[ButtonListener alloc] init] autorelease];
        btn.delegate = btnl;
        [btn click];
    }
    return 0;
}



Button.h
//
//  Button.h
//  Protocal
//
//  Created by Rayln Guan on 8/29/13.
//  Copyright (c) 2013 Rayln Guan. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ButtonDelegate.h"

@interface Button : NSObject
@property (nonatomic) id<ButtonDelegate> delegate;

- (void) click;

@end


Button.m
//
//  Button.m
//  Protocal
//
//  Created by Rayln Guan on 8/29/13.
//  Copyright (c) 2013 Rayln Guan. All rights reserved.
//

#import "Button.h"

@implementation Button

- (void) click{
    [_delegate onClick];
}

- (void) dealloc{
    NSLog(@"Button destory!!");
}

@end


ButtonDelegate.h
//
//  ButtonDelegate.h
//  Protocal
//
//  Created by Rayln Guan on 8/29/13.
//  Copyright (c) 2013 Rayln Guan. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol ButtonDelegate <NSObject>
//必须实践得方法
@required
- (void) onClick;

//可不实线得方法
@optional
- (void) test;
- (void) test2;
@end


ButtonListener.h
//
//  ButtonListener.h
//  Protocal
//
//  Created by Rayln Guan on 8/29/13.
//  Copyright (c) 2013 Rayln Guan. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ButtonDelegate.h"

@interface ButtonListener : NSObject <ButtonDelegate>


@end


ButtonListener.m
//
//  ButtonListener.m
//  Protocal
//
//  Created by Rayln Guan on 8/29/13.
//  Copyright (c) 2013 Rayln Guan. All rights reserved.
//

#import "ButtonListener.h"

@implementation ButtonListener

- (void) onClick{
    NSLog(@"button click!!");
}

- (void) dealloc{
    NSLog(@"ButtonListener destory!!");
}

@end

你可能感兴趣的:(监听器)