What is the BOOL * stop argument for enumerateObjectsUsingBlock: used for?

Recently, I have been using enumerateObjectsUsingBlock: for my quick queries, and it's hard for me to understand the use of BOOL *stop in an enum block.

In reference states of the NSArray class

stop : reference to a boolean value. A block can set the value to YES to stop further processing of the array. The stop argument is an exception argument. You must set this boolean to only YES within the Block.

So, of course, I can add the following to my block to stop the enumeration:

 if (idx == [myArray indexOfObject:[myArray lastObject]]) { *stop = YES; } 

From what I was able to tell, explicitly setting *stop to YES has no negative side effects. The enumeration seems to automatically stop at the end of the array. So uses *stop really necessary in the block?

+75
enumeration objective-c cocoa-touch nsarray fast-enumeration
Sep 10 '12 at 19:05
source share
1 answer

The stop argument to a block allows you to prematurely stop the enumeration. This is equivalent to break from a normal for loop. You can ignore it if you want to go through each object in the array.

 for( id obj in arr ){ if( [obj isContagious] ){ break; // Stop enumerating } if( ![obj isKindOfClass:[Perefrigia class]] ){ continue; // Skip this object } [obj immanetizeTheEschaton]; } 



 [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if( [obj isContagious] ){ *stop = YES; // Stop enumerating return; } if( ![obj isKindOfClass:[Perefrigia class]] ){ return; // Skip this object } [obj immanentizeTheEschaton]; }]; 

This is an out parameter because it is a reference to a variable from the scope of the call. It should be installed inside your block, but read inside enumerateObjectsUsingBlock: like NSError , it is usually passed back to your code from infrastructure calls.

 - (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block { // NB: This is probably not how this method is actually implemented! // It is just to demonstrate how the out parameter operates! NSUInteger idx = 0; for( id obj in self ){ BOOL stop = NO; block(obj, idx++, &stop); if( stop ){ break; } } } 
+141
Sep 10 '12 at 19:09
source share



All Articles