1.第一种
实现
+ (void)getGoodsDetailDataWithGhseq:(NSString *)ghseq
oldCode:(NSString *)oldCode
dataTableView:(UITableView *)dataTableView
completion:(void (^)(XYGoodsInfo * xYGoodsInfo))completion{
//当block当作参数的类型定义的时候,不能写block名,只能写成(^) 暂时不知道是什么原因
传值
dispatch_async(dispatch_get_main_queue(), ^{
completion(goodsinfo);
});
这种写法的优点是简洁,当然上面是针对网络请求的,一般的话,也可以这样写,拿UIViewController举个例子,
1.1 h文件
#import <UIKit/UIKit.h>
@interface TwoViewController : UIViewController
- (instancetype)initCompletion:(void(^)(NSString *test))testBlock;
@end
1.2 m文件
1.3调用
2.另一种(其实也大同小异)
2.1 以方法的方式
先声明
typedef void(^SearchTouchBlock)(NSString *title);
声明属性持有
@property (nonatomic, copy) SearchTouchBlock searchTouchBlock;
方法对外
-(void)didTouchTheSearchBtn:(SearchTouchBlock)Block;
block传值
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
self.searchTouchBlock(self.searchTitle);
}
调用取值
[self.HeaderView didTouchTheSearchBtn:^(NSString *title) {
wself.tableview.mj_footer.state = MJRefreshStatePulling;
wself.isTouchSearch = YES;
wself.pageNum = 1;
wself.keyWord = title;
[wself requestListData];
}];
这种写法就是强大灵活,但是写法麻烦
2.2当然也有以属性的方式
2.2.1
h文件
#import <UIKit/UIKit.h>
//这样的话,h文件会多一点,因为要对外
typedef void(^testBlock)(NSString*test);
@interface TwoViewController : UIViewController
@property (nonatomic, copy) testBlock littleBlock;
@end
2.2.2 m文件
- (IBAction)clickTestButton:(id)sender {
if(_littleBlock != nil) {
_littleBlock(@"memeda");
}
[self.navigationController popViewControllerAnimated:YES];
}
2.2.3 调用
- (IBAction)clickBtn:(id)sender {
TwoViewController *vc = [TwoViewController new ];
vc.littleBlock = ^(NSString *test) {
NSLog(@"----%@",test);
};
[self.navigationController pushViewController:vc animated:YES];
}