Objective-C學習筆記 利用協議實現回呼函數

來源:互聯網
上載者:User

Objective-C學習筆記 利用協議實現回調函數是本文要介紹的內容,主要是實現一個顯示文字為測試的視圖,然後經過3秒鐘測試文字變為回調函數文字。相應的如下:

 

實現的代碼如下:

定義協議:

 
  1. #import <UIKit/UIKit.h>   
  2. @protocol NoteDelegate   
  3. //回呼函數   
  4. -(void)messageCallBack:(NSString *)string;   
  5. @end 

調用協議:

 
  1. #import <Foundation/Foundation.h>   
  2. #import "NoteDelegate.h"   
  3. @interface ManagerMessage : NSObject {   
  4.     id<NoteDelegate> *noteDelegate;   
  5. }   
  6. @property (nonatomic,retain) id<NoteDelegate> *noteDelegate;   
  7. -(void)startThread;   
  8. @end  
  9.  
  10. #import "ManagerMessage.h"   
  11. @implementation ManagerMessage   
  12. @synthesize noteDelegate;   
  13. //開始一個線程   
  14. -(void)startThread   
  15. {   
  16.  
  17.     [NSTimer scheduledTimerWithTimeInterval:3   
  18.                                      target:self   
  19.                                    selector:@selector(targetMethod:)   
  20.                                    userInfo:nil   
  21.                                     repeats:NO];   
  22. }   
  23. -(void)targetMethod:(NSString *)string   
  24. {   
  25.     if (self.noteDelegate!=nil) {   
  26.         //完成線程 調用回呼函數   
  27.         [self.noteDelegate messageCallBack:@"回呼函數"];   
  28.         }   
  29. }   
  30. @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. - (void)viewDidLoad {   
  12.     [super viewDidLoad];   
  13.     self.textView.text=@"測試";   
  14.     ManagerMessage *message=[[ManagerMessage alloc] init];   
  15.     //通知調用協議   
  16.     message.noteDelegate=self;   
  17.     [message startThread];   
  18.     [message release];   
  19. }   
  20. - (void)didReceiveMemoryWarning {   
  21.     [super didReceiveMemoryWarning];   
  22. }   
  23. - (void)viewDidUnload {   
  24.     self.textView=nil;   
  25. }   
  26. - (void)dealloc {   
  27.     [self.textView release];   
  28.     [super dealloc];   
  29. }   
  30. @end 

小結:Objective-C學習筆記 利用協議實現回呼函數的內容介紹完了,希望本文對你有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.