我有多个 GET
API 请求方法,它们在完成时调用完成 block 。这是一个例子。
- (void)getUserInfo
onSuccess:(void (^)(id))successBlock
onFailure:(void (^)(NSError *))failureBlock {
NSString *urlStr = [NSString stringWithFormat:@"%@/user/", baseUrl];
[manager GET:urlStr parameters:nil progress:nil
success:^(NSURLSessionTask *task, id responseObject) {
successBlock(responseObject);
}
failure:^(NSURLSessionTask *operation, NSError *error) {
failureBlock(error);
}];
}
但是,我注意到我在其他方法中重复了管理器GET
请求代码。我想创建另一种方法来处理所有请求并删除重复代码。 URL 似乎是唯一发生变化的东西。但是,有一个缺陷。我需要调用 successBlock
让方法知道请求已完成。
也许我需要完全走另一条路,做一些不同的事情。
最佳答案
您可以传递完成 block ,然后从处理所有 get 请求的 final方法中调用它们。为了简洁起见,我通常会制作将要重用的 typedef 的完成 block 。这是我的意思的一个例子(我添加了第二个示例方法,它也传递到中心 getRequestWithURLString:onSuccess:onFailure:
方法):
LLFakeManager.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef void (^_Nullable SuccessCompletionBlock)(id responseObject);
typedef void (^_Nullable FailureCompletionBlock)(NSError *error);
@interface LLFakeManager : NSObject
- (void)getUserInfoOnSuccess:(SuccessCompletionBlock)successBlock onFailure:(FailureCompletionBlock)failureBlock;
- (void)getBooksCheckedOutOnSuccess:(SuccessCompletionBlock)successBlock onFailure:(FailureCompletionBlock)failureBlock;
@end
NS_ASSUME_NONNULL_END
LLFakeManager.m
#import "LLFakeManager.h"
@interface LLFakeManager()
- (void)getRequestWithURLString:(NSString *)urlString
onSuccess:(SuccessCompletionBlock)successBlock
onFailure:(FailureCompletionBlock)failureBlock;
@end
@implementation LLFakeManager
- (void)getUserInfoOnSuccess:(SuccessCompletionBlock)successBlock onFailure:(FailureCompletionBlock)failureBlock {
NSString *urlStr = @"FakeUserUrlPath";
[self getRequestWithURLString:urlStr onSuccess:successBlock onFailure:failureBlock];
}
- (void)getBooksCheckedOutOnSuccess:(SuccessCompletionBlock)successBlock onFailure:(FailureCompletionBlock)failureBlock {
NSString *urlString = @"FakeBooksUrlPath";
[self getRequestWithURLString:urlString onSuccess:successBlock onFailure:failureBlock];
}
// central method that will handle all the get requests
- (void)getRequestWithURLString:(NSString *)urlString
onSuccess:(SuccessCompletionBlock)successBlock
onFailure:(FailureCompletionBlock)failureBlock {
// some fake implementation here to do your request, then use the completion block passed in from whatever other method
if (successBlock) {
successBlock(@"responseObjectPassedBackHere");
}
}
@end
调用它的例子:
LLFakeManager *manager = [[LLFakeManager alloc] init];
[manager getUserInfoOnSuccess:^(id _Nonnull responseObject) {
NSLog(@"Here's my response object = %@", responseObject);
} onFailure:^(NSError * _Nonnull error) {
// no implementation but same idea
}];
会产生这个日志:
Here's my response object = responseObjectPassedBackHere
本站:http://goshdarnblocksyntax.com是一个方便的 block 语法列表,可能对您也有帮助。
关于ios - Objective-C : Is there a way to call a completion block for a method in another method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53505952/