Objective-C學習筆記 利用協議實現回調函數
作者:佚名
本文介紹的是Objective-C學習筆記 利用協議實現回調函數,主要是以一個小實例來實現函數的回調,我們來看內容。
Objective-C學習筆記 利用協議實現回調函數是本文要介紹的內容,主要是實現一個顯示文字為測試的視圖,然后經過3秒鐘測試文字變為回調函數文字。相應的截圖如下:
實現的代碼如下:
定義協議:
- #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學習筆記 利用協議實現回調函數的內容介紹完了,希望本文對你有所幫助。
責任編輯:zhaolei
來源:
互聯網