dismissViewControllerAnimated后挑豌,completion傳值給上一個父視圖方法
視圖firstView和secendView磕蛇,點擊firstView上面的按鈕presentviewcontroller出secendView缕坎;secendView上有個按鈕碾盐,點擊按鈕dismissViewControllerAnimated备韧,并將某個值傳給firstView辞居,或不直接在firstView里面的viewWillAppear里面調(diào)用方法焙矛,而是直接通過在dismissViewControllerAnimated completion里面編輯代碼塊調(diào)用firstView里面的任何方法葫盼,該怎么做?
這個問題其實并不復(fù)雜村斟,如果你知道如何使用NSNotificationCenter實現(xiàn)起來還是非常簡單的贫导。
先說一下,secendView在dismissViewControllerAnimated后蟆盹,如何在進(jìn)入firstView后孩灯,自動調(diào)用firstView里面的任何方法
第一步:在secendView里面,點擊按鈕時調(diào)用一個方法逾滥,該方法為:
-(void)secendAction{
[self dismissViewControllerAnimated:YES completion:^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"do" object:self];
}];
}
上面代碼是將secendView dismissViewControllerAnimated掉峰档,然后自動注冊一個名為do的通知
注冊了這個名為的通知,你就可以在任何.m文件里面通過以下代碼調(diào)用到了:
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(handleColorChange:)
name:@"do"
object:nil];
上面的代碼的意思就是匣距,先找到已經(jīng)注冊過的名為do的通知面哥,然后再自動調(diào)用handleColorChange去處理,
所以:
第二步:在firstView里面的viewWillAppear方法里面寫入以下代碼:
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(handleColorChange:)
name:@"do"
object:nil];
handleColorChange方法為:
-(void)handleColorChange:(id)sender{
[self firstView里面方法]
}
看明白了吧毅待?在secendView里面我們不直接調(diào)用firstView里面的方法尚卫,而是通過通知來讓firstView自動調(diào)用自己里面的某個方法。
通過通知可以讓不同.m文件之間進(jìn)行方法和參數(shù)的傳遞
ok就下來說一下如何在dismissViewControllerAnimated后將secendView里面的值傳遞給firstView
第一步:在secendView里面尸红,點擊按鈕時調(diào)用一個方法吱涉,該方法為:
-(void)secendAction{
[self dismissViewControllerAnimated:YES completion:^{
[tools showToast:@"圖片信息提交成功" withTime:1500 withPosition:iToastGravityCenter];
[[NSNotificationCenter defaultCenter] postNotificationName:@"do" object:self userInfo:dictionary];
}];
}
userInfo:dictionary里面的dictionary就是你要傳遞的字典對象的值
第二步:在firstView里面的viewWillAppear方法里面寫入以下代碼:
NSNotificationCenter nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(handleColorChange:)
name:@"do"
object:nil];
handleColorChange方法為:
-(void)handleColorChange:(NSNotification)sender{
NSLog(@"%@",sender);
[self firstView里面方法]
}
-(void)handleColorChange:(NSNotification*)sender里面的sender就是你在secendView里面所傳遞的字典對象的值,簡單吧外里?怎爵!
*********************重點來了*********************
我在解析數(shù)據(jù)的時候發(fā)現(xiàn)一個問題,我存進(jìn)去的是一個可變數(shù)組盅蝗,但是獲取到的是一個通知類數(shù)據(jù)鳖链,我打印出來了是這樣的
我看到是一個字典裝的2個鍵值對,直接使用了
把這個(NSNotification*)sender強轉(zhuǎn)成dict來去這個值:
NSDictionary * dict = (NSDictionary *)sender;
self.mArray = dict[@"object"];
然而卻失敗了
我在網(wǎng)上找到了相關(guān)的解釋帖子墩莫,用下面的方法可以成功:
NSMutableArray * objectArr = [[NSMutableArray alloc]init];
objectArr = sender.object;(.后面就是跟的圖片上面這個NSNotification*的鍵名芙委,我這里是存到了object里面了)
self.mArray = objectArr;