gpt4 book ai didi

ios - 具有完成 block 的递归方法

转载 作者:行者123 更新时间:2023-11-28 19:31:55 28 4
gpt4 key购买 nike

我调用我的方法:

[self getBoundariesForFields:fields index:0 withCompletionBlock:^{
DLog(@"completionBlock fields: %@", fields);
}];

方法:

-(void)getBoundariesForFields:(NSArray *)fields index:(NSInteger)index withCompletionBlock:(void(^)())completionBlock {

if (index < fields.count) {
NSMutableDictionary *field = [fields objectAtIndex:index];

[self getBoundariesForField:field withCompletionBlock:^{
[self getBoundariesForFields:fields index:index + 1 withCompletionBlock:^{
}];
}];
}
else {
DLog(@"else statement fields: %@", fields);
completionBlock();
}

我收到“else statement fields:”日志,但“completionBlock Fields:”从未运行。

我猜这与保留问题有关;调用此递归循环的原始方法被取消引用,因此当调用 completionBlock 时,代码消失了。

我怎样才能避免这种情况?

最佳答案

该 block 正在运行,但对该方法的递归调用正在传递一个空 block ^{}。通过传递原始 block 参数修复...

-(void)getBoundariesForFields:(NSArray *)fields index:(NSInteger)index withCompletionBlock:(void(^)())completionBlock {

if (index < fields.count) {
NSMutableDictionary *field = [fields objectAtIndex:index];

[self getBoundariesForField:field withCompletionBlock:^{
// NOTICE change here...
[self getBoundariesForFields:fields index:index + 1 withCompletionBlock:completionBlock];
}];
} else {
DLog(@"else statement fields: %@", fields);
completionBlock();
}
}

关于ios - 具有完成 block 的递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43124230/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com