Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement whileTrue control flow method with Obj-C Blocks?

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...

like image 819
donalbain Avatar asked Sep 13 '26 10:09

donalbain


1 Answers

Here you have a couple of ideas,

Assuming your bool wrapper implements boolValue, a naive implementation could be:

-(void) whileTrueDo:(void (^)(void)) block{
    while ([self boolValue]) {
        block();
    }
}

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.

   __block int count = 0;
    OOBooleanBlock evaluationBlock =  ^BOOL{
        return count < 10;
    };
    [[OOBoolean booleanWithBlock:evaluationBlock] whileTrueDo: ^() {
        NSLog(count);
        count++;
    }];

//In OOBoolean 
+(OOBoolean*) booleanWithBlock:(OOBooleanBlock) evaluationBlock{
//Instantiate, set the evaluationBlock ivar and return the ooboolean object.
} 

-(void) whileTrueDo:(void (^)(void)) block{
    while (self.evaluationBlock()) {
        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

like image 185
Lio Avatar answered Sep 16 '26 09:09

Lio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!