How to use a stop condition in a block such as enumerateObjectsUsingBlock from the NSDictionary class?

I want to create a method in my class, for example enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) , from the NSDictionary class.

I have little knowledge about using blocks, but I have not been able to figure out how to make a stop condition that uses the enumerateObjectsUsingBlock function. Any suggestions?

+7
source share
2 answers

The stop flag is used as follows:

 [coll enumerateUsingBlock:^(id o, NSUInteger i, BOOL *stop) { if (... check for stop ... ) { *stop = YES; return; } }]; 

When the enumeration block returns, the collection checks *stop . If he is YES , he ceases to be listed.

It is implemented in this way, in contrast to the return value, since it allows parallel enumeration without checking the return value of the block (which can lead to overhead). That is, in a parallel enumeration, a collection can dispatch_async() an arbitrary number of simultaneous iterations and periodically check *stop . Whenever *stop switches to YES , it stops scheduling more blocks (this also means that the stop flag is not a hard stop, and some undefined number of iterations can still be in flight).

In your iterator, you can:

  BOOL stop = NO; for(...) { enumerationBlock(someObj, someIndex, &stop); if (stop) break; } 
+13
source

The following code defines a method that takes a block as a parameter and continues to execute it until the shouldStop block is set to NO block.

 - (void)myMethod:(void(^)(BOOL *stop))aBlock { BOOL shouldStop = NO; while (!shouldStop) { aBlock(&shouldStop); } } 

The explanation is quite simple. A block is a function that takes some parameters. In this case, we pass as a parameter a pointer to the BOOL variable that we own. In doing so, we allow the block to set this variable and - in this case - indicate that the loop should stop.

At this point, the passed block can do something like

 [self myMethod:^(BOOL *stop) { if (arc4random_uniform(1)) { *stop = YES; } }]; 
+6
source

All Articles