iOS -- block的正确使用

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;

@end

2.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];

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值