您的位置:首页 > 移动开发 > Objective-C

Objective-c利用协议实现回调函数

2013-03-31 12:46 330 查看
定义协议:

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: