如何使用 Obj-C 块实现 whileTrue 控制流方法?
是否可以使用块在 Objective-C 中实现类似 Smalltalk 风格的 whileTrue: 方法?具体来说,而不是:
int count = 0;
while (count < 10)
{
NSLog(count);
count++;
}
我希望能够(通过称为 OOBoolean 的 bool 原语上的包装器)执行类似...
__block int count = 0;
[[OOBoolean booleanWithBool: count < 10] whileTrueDo: ^() {
NSLog(count);
count++;
}];
我无法理解这是如何实现的...
Is it possible to implement something like a Smalltalk-style whileTrue: method in Objective-C using blocks? Specifically, instead of:
int count = 0;
while (count < 10)
{
NSLog(count);
count++;
}
I'd like to be able to do (via a wrapper on the bool primitive called OOBoolean) something like...
__block int count = 0;
[[OOBoolean booleanWithBool: count < 10] whileTrueDo: ^() {
NSLog(count);
count++;
}];
I'm having trouble understanding how this would be implemented though...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里你有几个想法,
假设你的 bool 包装器实现 boolValue,一个简单的实现可能是:
为了让包装器在每次迭代后更改其 bool 值,该块必须能够实际更改用于计算的变量布尔条件。因此,在您的情况下,通过将 __block 类型修饰符设置为 count,并增加每个块执行中的计数,您应该能够使其工作。
问题是,如果您通过发送评估条件来创建包装器,正如您在问题中所述,您将无法在每次迭代中更改其 bool 值。因此,我将更改包装器的创建方式和 whileTrueDo: naive 实现,以便布尔包装器使用评估块。
记得使用__block类型修饰符,否则会进入无限循环。
我还没有测试过这个,但我希望这对你有帮助。
干杯
Here you have a couple of ideas,
Assuming your bool wrapper implements boolValue, a naive implementation could be:
In order for the wrapper to change its bool value after each iteration, the block must be able to actually change the variable that is used to calculate the boolean condition. So, in your case, by setting the __block type modifier to count, and increasing count in each block execution, you should be able to make it work.
The problem is, if you create your wrapper by sending the evaluated condition, as you stated in your question, you wont be able to change its bool value in each iteration. So, I would change the way the wrapper is created and the whileTrueDo: naive implementation so the boolean wrapper uses an evaluation block.
Remember to use the __block type modifier, otherwise you will enter in an infinite loop.
I haven't tested this, I hope this helps you though.
Cheers