实现的代码如下:
定义协议:
1 #import <UIKit/UIKit.h> 2 @protocol NoteDelegate 3 //回调函数 4 -(void)messageCallBack:(NSString *)string; 5 @end 6 //调用协议 7 #import <Foundation/Foundation.h> 8 #import "NoteDelegate.h" 9 @interface ManagerMessage : NSObject { 10 id<NoteDelegate> *noteDelegate; 11 } 12 @property (nonatomic,retain) id<NoteDelegate> *noteDelegate; 13 -(void)startThread; 14 @end
1 #import "ManagerMessage.h" 2 @implementation ManagerMessage 3 @synthesize noteDelegate; 4 //开始一个线程 5 -(void)startThread 6 { 7 8 [NSTimer scheduledTimerWithTimeInterval:3 9 target:self 10 selector:@selector(targetMethod:) 11 userInfo:nil 12 repeats:NO]; 13 } 14 -(void)targetMethod:(NSString *)string 15 { 16 if (self.noteDelegate!=nil) { 17 //完成线程 调用回调函数 18 [self.noteDelegate messageCallBack:@"回调函数"]; 19 } 20 } 21 @end
前台页面实现:
1 #import "IphoneDeleteViewController.h" 2 #import "ManagerMessage.h" 3 @implementation IphoneDeleteViewController 4 @synthesize textView; 5 6 //回调函数 7 -(void)messageCallBack:(NSString *)string 8 { 9 self.textView.text=string; 10 } 11 12 - (void)viewDidLoad { 13 [super viewDidLoad]; 14 self.textView.text=@"测试"; 15 ManagerMessage *message=[[ManagerMessage alloc] init]; 16 //通知调用协议 17 message.noteDelegate=self; 18 [message startThread]; 19 [message release]; 20 } 21 22 - (void)didReceiveMemoryWarning { 23 [super didReceiveMemoryWarning]; 24 } 25 26 - (void)viewDidUnload { 27 self.textView=nil; 28 } 29 30 - (void)dealloc { 31 [self.textView release]; 32 [super dealloc]; 33 } 34 35 @end
通过以上几步我们基本可以实现回调函数的实现