gpt4 book ai didi

objective-c - 使用指针更改 block 中的值是否安全?

转载 作者:太空狗 更新时间:2023-10-30 03:40:51 27 4
gpt4 key购买 nike

我已经开始使用 block ,我遇到的第一件事是无法设置由闭包捕获的值。这很好,我已经使用 C/C++ 很长时间了。我只会使用指针!

MyObject* bestObj = nil;
float bestDist= 10000.f;

MyObject **pBestObj = &bestObj;
float* pBestDist = &bestDist;

[self testObjects:class block:^(MyObject* obj){

CGRect r = [obj boundingBox];
// position is captured from outside this code sample
if( CGRectContainsPoint( r, position ) )
{
float dist = GetDistance( obj, position );

if(dist < bestDist)
{
*pBestDist = dist;
*pBestObj = obj;
}
}
}];

return bestObj;

我的问题是,这样安全吗?我假设只要我的指针指向没有超出范围并且仍然存在的东西,它就应该起作用。但我也假设那些占用 block 的东西永远不会,比如说,并行运行它们。我知道我的代码没有,但我不知道,比如说,使用带有 NSArray enumerateObjectsUsingBlock 调用的 block 。

最佳答案

做到这一点的“正确”方法是将那些原始变量标记为 block 可变,__block

关于objective-c - 使用指针更改 block 中的值是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6720542/

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