1. 程式人生 > >Objective-c利用協議實現回撥函式

Objective-c利用協議實現回撥函式

定義協議:

#import <UIKit/UIKit.h> 

@protocol myViewDelegate

-(void) CallBackFun;

@end

呼叫協議:
#import <Foundation/Foundation.h>
#import "myViewDelegate.h"

@interface Test : NSObject{
    id<myViewDelegate> delegate; 
}

@property(nonatomic,retain) id<myViewDelegate> delegate;

-(void)callback;

@end
#import "Test.h"

@implementation Test
@synthesize delegate;

-(id)init{
    NSLog(@"init!");
    return [super init];
}

-(void)callback
{
    NSLog(@"callbackInTest!");
    if (delegate!=nil) {
        [delegate CallBackFun];
    }

}
@end

實現協議,接受回撥:
#import <UIKit/UIKit.h>
#import "myViewDelegate.h"

@interface ViewController : UIViewController<myViewDelegate>

@end
//
//  ViewController.m
//  CallBackDemo
//
//  Created by apple on 13-3-31.
//  Copyright (c) 2013年 apple. All rights reserved.
//

#import "ViewController.h"
#import "Test.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
        
    Test *test =  [[Test alloc]init];
    test.delegate=self;
    [test callback];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) CallBackFun
{
    NSLog(@"CallBack!");
}

@end