我试图使用块来创建递归。它一开始运行良好,但最终会崩溃并显示一个无法访问的异常。这是我的代码:
BOOL (^Block)(Square *square, NSMutableArray *processedSquares) = ^(Square *square, NSMutableArray *processedSquares) {
[processedSquares addObject:square];
if (square.nuked) {
return YES; // Found a nuked square, immediately return
}
for (Square *adjacentSquare in square.adjacentSquares) {
if ([processedSquares containsObject:adjacentSquare]) {
continue; // Prevent infinite recursion
}
if (Block(adjacentSquare, processedSquares)) {
return YES;
}
}
return NO;
};
__block NSMutableArray *processedSquares = [NSMutableArray array];
BOOL foundNukedSquare = Block(square, processedSquares);
说明:我有一个Square类,其中包含一个BOOL类型的nuked变量和一个包含其他Squares的NSArray类型的adjacentSquares数组。
我想检查一个方块或其“连接”的方块是否已被毁坏。 processedSquares数组用于跟踪我已经检查过的方块,以防止无限递归。
当我运行此代码时,它会执行很多次这个块(如预期的那样)。但是在最后一行发生了错误访问异常时,它会崩溃。
控制台还会出现以下内容:
不能访问地址0x1 不能访问地址0x1 不能访问地址0x1 不能访问地址0x1 警告:取消调用-当前线程堆栈上的objc代码使其不安全。
我对块和递归不是很熟悉。有什么想法?
编辑1
按要求,下面是回溯信息:
#0 0x00000001 in ??
#1 0x000115fb in -[Square connectedToNukedSquare] at Square.m:105
#2 0x00010059 in __-[Bot makeMove]_block_invoke_1 at Bot.m:94
#3 0x91f3f024 in _dispatch_call_block_and_release
#4 0x91f31a8c in _dispatch_queue_drain
#5 0x91f314e8 in _dispatch_queue_invoke
#6 0x91f312fe in _dispatch_worker_thread2
#7 0x91f30d81 in _pthread_wqthread
#8 0x91f30bc6 in start_wqthread
__block
)。 - bbum