1. block相关内容 …………………………………….. …………………………………….. …………………………………….. …………………………………….. …………………………………….. …………………………………….. …………………………………….. …………………………………….. 2. block的使用 block的使用步骤:
1.正确声明 block
2.判断block是否被实现
3.block的调用
2.1 block的书写
#import <UIKit/UIKit.h> //=================通用(1,2,3可直接把完整的block改为block名,为了加深印象暂时不用改名) //=================通用 typedef void(^choiceCity3)(NSString *cityStr); @interface SearchController : UIViewController @property(nonatomic, strong)NSArray * dataArry;//存放所有的城市信息 //=================1 @property (nonatomic, copy) void(^choiceCity1)(); //=================2 @property (nonatomic, copy) void(^choiceCity2)(NSString * cityStr); //================3 @property(nonatomic, copy)choiceCity3 choiceCity3; - (void)choiceCityComplete:(void(^)(NSString *cityStr)) choiceCity3; @end2.2 block的判断 //在需要调用block的地方先判断block是否被实现。如果不做判断将会出错. (可理解为:如果(block)方法有被实现了,那么就执行该方法(block))。 所以如果没有判断该方法是否被实现就去执行方法自然会错咯
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ NSArray * currentCityArray = self.citysArray[indexPath.section]; ModelCity *currentCity = currentCityArray[indexPath.row]; if (self.choiceCity1) { self.choiceCity1(); } if (self.choiceCity2) { self.choiceCity2(currentCity.name); } if (self.choiceCity3) { self.choiceCity3(_test3);//点击选择了才去执行block } [self dismissViewControllerAnimated:YES completion:nil]; } - (void)choiceCityComplete:(void (^)(NSString *))choiceCity3{ self.choiceCity3 = choiceCity3; }2.3 block的调用
- (void)presentVC{ SearchController *searchVC = [[SearchController alloc]init]; searchVC.dataArry = _cityArray; searchVC.choiceCity1=^(){ NSLog(@"无参调用,在这里执行你想做的事"); }; searchVC.choiceCity2=^(NSString *cityName){ NSLog(@"属性参数:%@",cityName); }; [searchVC choiceCityComplete:^(NSString *cityStr) { NSLog(@"传来的参数是:%@",cityStr); _choiceLabel.text = cityStr; }]; [self presentViewController:searchVC animated:YES completion:nil]; }