我有三个功能。请注意,这些是伪代码:
函数 validateService 将执行验证服务,之后将在回调中调用 runService 。也就是说,runService将在验证服务完成后执行。
函数 callService 将调用 validateService 。一旦 runService 完成执行,它将返回URLSessionDataTask,它将由 callService 返回。
问题:如何从 callService 中的 runService 获取NSURLSessionDataTask?哪个选项更好实现?还有另一种(更简单/更好)的方式,我没有想到我可以从 callService 中的 runService 获取NSURLSessionDataTask对象吗?
选项1:使用传递引用
问题:此代码失败,因为dataTask需要__autoreleasing,但是当我添加__autoreleasing时,我收到错误:无法捕获块中的__autoreleasing变量
//NOTE: THIS PART IS OBJ-C
(NSURLSessionDataTask *)callServicewithSuccess:(SuccessHandler)successBlock
andFail:(FailHandler)errorBlock
{
NSURLSessionDataTask* dataTask;
[WMTValidateUserService validateService:^{
[self runServicewithSuccess: successBlock
andFail:errorBlock
andDataTask:&dataTask];
} failBlock:^{
[self runServicewithSuccess: successBlock
andFail:errorBlock
andDataTask:&dataTask];
}];
return dataTask;
}
- (void)runServicewithSuccess:(SuccessHandler)successBlock
andFail:(FailHandler)errorBlock
andDataTask:(NSURLSessionDataTask**)dataTask
{
*dataTask = someExpression;
}
//NOTE: THIS PART IS IN SWIFT
class func validateService(_ successBlock: @escaping () -> (), failBlock: @escaping () -> () )
{
ServiceHandler.shared().getValidateUser(success: { _ -> Void in successBlock() },
fail: { _ -> Void in failBlock() })
}
选项2:使用按值传递
问题:runService返回NSURLSessionDataTask,但callService中的回调不允许我获取该对象。
问题:如何编写validateService以便返回NSURLSessionDataTask?
//NOTE: THIS PART IS OBJ-C
(NSURLSessionDataTask *)callServicewithSuccess:(SuccessHandler)successBlock
andFail:(FailHandler)errorBlock
{
NSURLSessionDataTask* dataTask;
[WMTValidateUserService validateService:^{
[self runServicewithSuccess: successBlock
andFail:errorBlock
andDataTask:dataTask];
} failBlock:^{
[self runServicewithSuccess: successBlock
andFail:errorBlock
andDataTask:dataTask];
}];
return dataTask;
}
- (NSURLSessionDataTask *)runServicewithSuccess:(SuccessHandler)successBlock
andFail:(FailHandler)errorBlock
andDataTask:(NSURLSessionDataTask*)dataTask
{
dataTask = someExpression;
return dataTask;
}
//NOTE: THIS PART IS IN SWIFT
class func validateService(_ successBlock: @escaping () -> (), failBlock: @escaping () -> () )
{
ServiceHandler.shared().getValidateUser(success: { _ -> Void in successBlock() },
fail: { _ -> Void in failBlock() })
}
谢谢