[iOS]Block(二)回呼機制

  • 837
  • 0
  • iOS
  • 2015-04-02

摘要:[iOS]Block與GCD多執行緒運用(二)

另外一種Block常見的運用,就是回呼機制。也可以想像成當事件觸發時的事件Handler。這一篇以一個簡單的範例來展現。

 

在Xcode專案中,建立一個使用Storyboard的專案,並且拖拉Navigation Controller與兩個View到畫面中。在第一個View裡面建立一個Label與Button物件。當按下第一個Button時,將畫面push到第二的View。在第二個View裡面建立一個Text Field。

 

先來看到第二個View,這邊為第二個View建立一個相對應的ViewController,這邊我命名為HeaderViewController。在HeaderViewController.h檔案宣告下方程式碼:

#import 
//建立一個Block指標同意詞
typedef void (^ReturnTextBlock)(NSString *showText);

@interface HeaderViewController : UIViewController
//建立一個property,回傳Block指標位置
@property (nonatomic, copy) ReturnTextBlock returnTextBlock;
//建立一個方法,帶入一個ReturnTextBlock Block指標,
- (void)returnText:(ReturnTextBlock)block;

@property (weak, nonatomic) IBOutlet UITextField *inputTF;

@end

 

在HeaderViewController.m檔案裡面建立底下的實作:

#import "HeaderViewController.h"
@interface HeaderViewController ()
@end

@implementation HeaderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
}

//函數:returnText,帶入一個Block指標:ReturnTextBlock
- (void)returnText:(ReturnTextBlock)block {
    self.returnTextBlock = block;
}

//實作當畫面要離開時的viewWillDisappear事件
- (void)viewWillDisappear:(BOOL)animated {
    
    if (self.returnTextBlock != nil) {
        self.returnTextBlock(self.inputTF.text);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

@end

 

第一個View依照預設值,對應到ViewController。在ViewController.h檔案中宣告一個property,

對應到Label。

@property (weak, nonatomic) IBOutlet UILabel *showLabel;

 

在ViewController.m檔案裡面的實作:

#import "ViewController.h"
#import "HeaderViewController.h"

@interface ViewController ()

@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

//實作當要push到下一個View前會觸發的prepareForSegue事件
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    HeaderViewController *tfVC = segue.destinationViewController;
    
    //回呼下一個ViewController的returnText函數,函數需要帶入一個NSString
    [tfVC returnText:^(NSString *showText) {
        self.showLabel.text = showText;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

 

編譯這個App,可以看到當你在第二個View裡面的Text Field裡面輸入文字後,back回上一頁時,你輸入的值被帶回了上一個View,並且顯示在Label中。

    

 

 

實務上,在兩個View之間的資料傳遞,會有更簡單的方法,就是直接存取物件的屬性,而不需要這麼大費周章。不過Block的回呼機制在許多地方是非常好用的。例如當你利用UITableView要從網站上大量的下載資料。這個動作一般你會設計成非同步執行。而當下載完成的時候,你會需要做一些特定動作的執行,這時候回呼機制就會非常好用。

 

參考文獻:

iOS开发:使用Block在两个界面之间传值(Block高级用法:Block传值)

http://winann.blog.51cto.com/4424329/1438480