寫給正在學習iOS中的同學,如若措辭有什么不妥,或者邏輯有問題,歡迎在下方批評指正,謝謝.
(o)/~
在iOS開發(fā)中,我們在兩個控制器之間正向傳數(shù)據(jù)的時候,一般使用的是屬性(property),因為這樣最簡單,最方便,也最快速.
但有時候,或者說有很多時候,我們需要逆向傳遞數(shù)據(jù),也就是當前控制器Dismiss返回上一個控制器時,在當前控制器處理過的數(shù)據(jù)需要返回給Source Controller,這種數(shù)據(jù)傳遞,在OC中一般有三種方式:通知靶病、代理炕淮、Block卢鹦;
1.通知
在第二個控制器觸發(fā)Dismiss時,發(fā)出通知,同時
- (void)clickDismissButton:(UIButton *)button
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"buttonData" object:nil userInfo:@{@"button":button}];
[self dismissViewControllerAnimated:YES completion:nil]; //也可以在completion的block發(fā)出此通知,在此我們不使用回調(diào),給的nil
}
第一個控制器監(jiān)聽此通知即可
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitleText:) name:@"buttonData" object:nil];
}
- (void)setTitleText:(NSNotification *)notify
{
UIButton *button = notify.userInfo[@"button"];
self.receiveLabel.text = button.currentTitle; //我們修改了第一個控制器上一個label的text和背景顏色
self.receiveLabel.backgroundColor = button.backgroundColor;
}//通知很簡單
2.代理
因為我們目的是要給第一個控制器傳遞數(shù)據(jù)修改屬性,但是第二個控制器做不到修改第一個控制器控件屬性這件事兒,所以,我們需要在第二個控制器寫出協(xié)議,并設(shè)置代理屬性,在第一個控制器設(shè)置代理,遵循協(xié)議,實現(xiàn)方法,也很簡單.
@class HOModalController;
@protocol HOModalControllerDelegate <NSObject>
@optional
- (void)modalController:(HOModalController *)modalVC withButton:(UIButton *)button;
@end
@interface HOModalController : UIViewController
@property (weak, nonatomic) id <HOModalControllerDelegate> delegate;
@end
并在.m文件中調(diào)用代理方法
if ([self.delegate respondsToSelector:@selector(modalController:withButton:)])
{
[self.delegate modalController:self withButton:button];
}
在第一個控制控制器中實現(xiàn)代理方法
- (void)modalController:(HOModalController *)modalVC withButton:(UIButton *)button
{
self.receiveLabel.text = button.currentTitle;
self.receiveLabel.backgroundColor = button.backgroundColor;
}//也很簡單
3.Block
在控制器dismiss的時候,調(diào)用block傳值,首先,我們在第二個控制器定義一個外部可訪問的block屬性,也就是.h文件里
@property (copy, nonatomic) void(^modalBlock)(UIButton *button);
然后在.m文件中給此屬性賦值
self.modalBlock(button);
接著在第一個控制器中調(diào)用這個屬性即可
modalVC.modalBlock = ^(UIButton *button){
self.receiveLabel.text = button.currentTitle;
self.receiveLabel.backgroundColor = button.backgroundColor;
};
這只是最簡單的block作為屬性傳值,還有更復雜更高級的block應(yīng)用等我學到了我再給大家寫篇文.
(≧▽≦)/