在IOS中,有些情況是用代理實現反向傳值的,現在介紹一種更爲簡單的傳值方式,是Block傳值方式,Block在IOS中代碼有點生澀,理解起來有點困難,但是寫法確實比代理方式方便太多。
下面貼上相關代碼,爲以後學習作爲標記:
第一個頁面相關代碼:
//點中右上角按鍵
-(void)addCity:(UIBarButtonItem*)sender {
//跳轉到添加界面
AddViewController *addVc = [[AddViewController alloc]init];
//設置block屬性
//block 本身就是函數 只是是 匿名函數
addVc.block = ^(City *city) {
//將 新城市添加到數組中
[self.allcities addObject:city];
//刷新 tableview
[self.tableView reloadData];
};
[self.navigationController pushViewController:addVc animated:YES];
}
第二個頁面(傳值的頁面)相關代碼:
AddViewController.h
#import <UIKit/UIKit.h>
#import "City.h"
//1.給Block類型起個別名
typedef void(^ADD_BLOCK)(City*);
@interface AddViewController : UIViewController
//2.添加Block屬性 //MRC用copy ARC用strong
@property(nonatomic,strong)ADD_BLOCK block;
@end
AddViewController.m頁面:
- (IBAction)addCity:(id)sender {
City *city = [[City alloc]init];
city.name = self.nameField.text;
city.population = [self.populationField.text intValue];
//3.適當的時候通過 block 把值傳出去
self.block(city);
//把新的城市 傳給代理人(前一個界面)
// [self.delegate addCity:self inputCity:city];
//委託 是傳過來 一個代理對象,通過代理對象執行代理方法
//Block 是傳過來一個 一個執行方法
//返回前一個界面
[self.navigationController popViewControllerAnimated:YES];
}