Objective-C利用协议实现回调函数(类似java的回调函数)
實現的代碼如下:
定義協議:
#import?<UIKit/UIKit.h>
@protocol?NoteDelegate
//回調函數
-(void)messageCallBack:(NSString?*)string;
@end
調用協議
????#import?<Foundation/Foundation.h>
????#import?"NoteDelegate.h"
????@interface?ManagerMessage?:?NSObject?{
????????id<NoteDelegate>?*noteDelegate;
????}
????@property?(nonatomic,retain)?id<NoteDelegate>?*noteDelegate;
????-(void)startThread;
????@end
????#import?"ManagerMessage.h"
????@implementation?ManagerMessage
????@synthesize?noteDelegate;
????//開始一個線程
????-(void)startThread
????{
????????[NSTimer?scheduledTimerWithTimeInterval:3
?????????????????????????????????????????target:self
???????????????????????????????????????selector:@selector(targetMethod:)
???????????????????????????????????????userInfo:nil
????????????????????????????????????????repeats:NO];
????}
????-(void)targetMethod:(NSString?*)string
????{
????????if?(self.noteDelegate!=nil)?{
????????????//完成線程?調用回調函數
????????????[self.noteDelegate?messageCallBack:@"回調函數"];
????????????}
????}
????@end
前臺頁面實現:
????#import?"IphoneDeleteViewController.h"
????#import?"ManagerMessage.h"
????@implementation?IphoneDeleteViewController
????@synthesize?textView;
????//回調函數
????-(void)messageCallBack:(NSString?*)string
????{
????????self.textView.text=string;
????}
????-?(void)viewDidLoad?{
????????[super?viewDidLoad];
????????self.textView.text=@"測試";
????????ManagerMessage?*message=[[ManagerMessage?alloc]?init];
????????//通知調用協議
????????message.noteDelegate=self;
????????[message?startThread];
????????[message?release];
????}
????-?(void)didReceiveMemoryWarning?{
????????[super?didReceiveMemoryWarning];
????}
????-?(void)viewDidUnload?{
????????self.textView=nil;
????}
????-?(void)dealloc?{
????????[self.textView?release];
????????[super?dealloc];
????}
????@end
總結
以上是生活随笔為你收集整理的Objective-C利用协议实现回调函数(类似java的回调函数)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: word中如何多次使用格式刷
- 下一篇: Reachability,ios检测网络