How to break a block loop in Objective-C?

I have these declarations in the header file:
Note: I will not explain all the code, I think it is easy to understand

typedef void (^loopCell)(id cell); -(id)allCells:(loopCell)cell; 

And the implementation of allCells :

 -(id)allCells:(loopCell)cell { for (AAFormSection *section in listSections) { for (id _cell in section.fields) { cell(_cell); } } return nil; } 

Using the allCells function:

 -(void)setFieldValue:(NSString *)value withID:(int)rowID { [self allCells:^(id cell) { if([cell isKindOfClass:[AAFormField class]]) { AAFormField *_cell = (AAFormField *)cell; if(_cell.rowID == rowID) { _cell.value = value; //return; Here I want to terminate loop } } }]; } 

My problem is , I cannot complete the allCells loop in the middle (in fact, when I found the object that I need in the loop, I don't want to go through other objects)

How can I stop the allCells cycle in the middle?

+4
source share
2 answers

Check out the docs on NSArray enumerateObjectsUsingBlock: They set the block signature to take the BOOL pointer. Set the BOOL stop to YES to stop the iteration.

 typedef void (^loopCell)(id cell, BOOL *stop); -(id)allCells:(loopCell)cell { BOOL stop = NO; for (AAFormSection *section in listSections) { for (id _cell in section.fields) { cell(_cell, &stop); if (stop) { break; } } if (stop) { break; } } return nil; } -(void)setFieldValue:(NSString *)value withID:(int)rowID { [self allCells:^(id cell, BOOL *stop) { if([cell isKindOfClass:[AAFormField class]]) { AAFormField *_cell = (AAFormField *)cell; if(_cell.rowID == rowID) { _cell.value = value; if (stop) { *stop = YES; } } } }]; } 
+9
source

You cannot exit setFieldValue , but you can from allCells .

Prior to this method that you use, it calls the block - allCells in this case - to provide a mechanism to stop the loop. This is usually a parameter for a block.

If allCells is yours and you do not mind modifying it, you change the signature of the block to take a pointer to a BOOL initialized by YES and check if the block has changed its value to NO.

(Note: you can break from the for in loop.)

+1
source

Source: https://habr.com/ru/post/1443150/


All Articles