我正在从同步调用转移到异步调用,并想知道实现条件异步请求的好方法是什么?
例如,我有以下方法:
-(void)getSomeData:(NSInteger)data
{
[Set data which will be used in the layout]
if (data == 1)
{
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
[Set data which will be used in the layout]
[Do Some layout calls]
}
}
[Do Some layout calls]
}
在获取数据异步时,以及在不满足条件时,需要执行[Do some layout calls]。
我有很多像这样的方法,似乎它会产生很多“重复”的代码,或者需要大量的方法提取。
答案 0 :(得分:1)
您可以使用块来避免代码重复。
- (void)getSomeData:(NSInteger)data
{
void(^setData)(void) = ^(void) {
[Set data which will be used in the layout]
};
void(^doLayoutJob)(void) = ^(void) {
[Do Some layout calls]
};
setData();
if (data == 1)
{
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
setData();
doLayoutJob();
}
}
doLayoutJob();
}
答案 1 :(得分:0)
在完成块中获取数据,然后调用将设置数据并执行一些布局的函数。您可以根据您的条件调用get data completion block。
- (void)setUp
{
NSData *data = nil;
[self setUpData:data];
if (data)
{
[self getDataFromUrlString:@"URL" dataCompletion:^(id data) {
[self setUpData:data];
}];
}
}
- (void)setUpData:(id)data
{
[Set data which will be used in the layout];
[Do Some layout calls]
}
- (void)getDataFromUrlString:(NSString *)urlString dataCompletion:(void(^)(id data))dataCompletion {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
dispatch_sync(dispatch_get_main_queue(), ^(void) {
dataCompletion(data);
});
});
}