2014年8月20日 星期三

Pass Value by NSNotificationCenter programmatically using Swift and Object-C language

【說明】

先前已經會了使用自訂DelegateBlock的方式來將值回傳,這次我們將要使用NSNotificationCenter來達到這樣的目的。

iOS有五種傳值的方式:
1.  建立對方Class的實體變數,取得物件後做getter/setter。
2.  利用target-action的機制,傳值給func。
3.  自訂Delegate。
4.  Block。
5.  NSNotificationCenter。

比較自訂Delegate、Block與NSNotificationCenter:
自訂Delegate:需要六步驟,需倚靠prepareForSegue取得Class的指標。
Block:需要三步驟,需倚靠prepareForSegue取得Class的指標。
NSNotificationCenter:需要兩步驟,不需倚靠prepareForSegue取得Class的指標,若不需監聽通知需要移除註冊的通知。

使用NSNotificationCenter回傳值的兩步驟:
1.  向NSNotificationCenter註冊一個Notification。
2.  當事件發生時,發送Notification給NSNotificationCenter。


【專案開發步驟】

建立專案:

使用Single View Application模板建立一個名為Notification的專案,使用iPhone裝置。

設計使用者介面:

替View加入NavigationController,並完成介面的設計,並將會用到的元件與對應的ViewController做連結,如下圖所示。

設計使用者介面

建立並修改B ViewController:

新增Class,並取名為DetailViewController,並與Storyboard內的ViewController做連結,如下圖所示。

<Swift>
宣告Storyboard內的ViewController的Class是誰_Swift
<Object-C>
宣告Storyboard內的ViewController的Class是誰_Object-C


當事件發生時,發送Notification給NSNotificationCenter,如下所示。

<Swift>
@IBAction func click(sender: UIButton) {
    NSNotificationCenter.defaultCenter().postNotificationName("SendName", object: nameTextField.text)
    self.navigationController.popToRootViewControllerAnimated(1);
}

<Object-C>
- (IBAction)click:(UIButton *)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SendName" object:self.nameTextField.text];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
當按鈕按下後執行func名為click的func。發送Notification給NSNotification,並帶物件nameTextField的文字。用NavigationController回到RootViewController。

修改A ViewController:

將Class名改為MainViewController,並與Storyboard內的ViewController做連結,如下圖所示。

<Swift>
宣告Storyboard內的ViewController的Class是誰_Swift
<Object-C>
宣告Storyboard內的ViewController的Class是誰_Object-C

向NSNotificationCenter註冊一個監聽者,於ViewDidLoad內加入程式碼,如下所示。

<Swift>
NSNotificationCenter.defaultCenter().addObserverForName("SendName", object: nil, queue: NSOperationQueue.mainQueue()) { (NSNotification) -> Void in
    self.nameLabel.text = NSNotification.object as String
}

<Object-C>
[[NSNotificationCenter defaultCenter] addObserverForName:@"SendName" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
    self.nameLabel.text = note.object;
}];
向NSNotificationCenter註冊一個監聽者,監聽名為SendName的Notification所發送的通知,使用mainQueue去執行工作,將收到的通知給nameLabel去顯示。


【執行結果】

    

    


【專案範例】

沒有留言:

張貼留言