- (void)loadTest:(NSString *)loadFunc sucess:(void(^)(NSString *))sucess failure:(void(^)(NSString *))failure { NSLog(@"11111111Test Func Start"); //@2 if (sucess) { //@3 //判斷sucess參數(不爲空) NSString *sucessString = @"Sucess String"; NSLog(@"333333333 Run Block Sucess"); sucess(sucessString); //@3-1.此時跳轉到 @3-2 } NSString *failureString = @"Failure String"; NSLog(@"5555555555555 Run Block Failure"); //@4 if(failure) //@5 判斷failure參數(爲空) failure(failureString); } - (void)startLoading{ [self loadTest:@"startLoading" sucess: ^(NSString * loadSucess) { //@3-2 NSLog(@"22222222 loading sucess"); } failure:nil // ^(NSString * loadFailure) { // NSLog(@"44444444 loading failure"); // } ]; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self startLoading]; //@1 }
輸出以下 async
2015-03-18 09:48:18.453 testBarItem[2326:214237] 11111111Test Func Start 2015-03-18 09:48:18.454 testBarItem[2326:214237] 333333333 Run Block Sucess 2015-03-18 09:48:18.454 testBarItem[2326:214237] 22222222 loading sucess 2015-03-18 09:48:18.454 testBarItem[2326:214237] 5555555555555 Run Block Failure
//示例: (void)loadData{ [self startLoading]; if (self.isRecord) { [[GoodsService sharedGoodsService] loadGoodsWithGoodsId:self.gid success:^(Goods *goodsResult) { dispatch_async(dispatch_get_main_queue(), ^{ self.goods = goodsResult; if (self.goods) { [self initContentView]; } [self stopLoading]; }); } failure:^(NSError *error) { [self stopLoading]; [self showError:error]; }]; } - (void)loadGoodsWithGoodsId:(LLInt)gid success:(void (^)(Goods *))success failure:(void (^)(NSError *))failure{ NSDictionary *param = @{ @"goodsId":@(gid)}; [[TcpService sharedTcpService] requestWithCmd:CMD_GOODS_ONE params:param success:^(::com::iwgame::xaction::proto::XActionResult *result) { if (result->rc() == 0) { Goods *goods = [[Goods alloc] init]; if (result-> HasExtension(com::iwgame::msgs::proto::goods)) { const com::iwgame::msgs::proto::Goods& goodsPB = result->GetExtension(com::iwgame::msgs::proto::goods); goods = [self buildGoodsWithGoodsPB:goodsPB]; } if (success) { success(goods); } }else{ failure(NE(result->rc())); } } failure:^(NSError *error) { if (failure) { failure(error); } }]; }