Friday, May 31, 2013

NSArray enumerateObjectsUsingBlock example in Objective C (iOS).

NSArray enumerateObjectsUsingBlock

Executes a given block using each object in the array, starting with the first object and continuing through the array to the last object.

- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block

The block to apply to elements in the array.
The block takes three arguments:
The element in the array.
The index of the element in the array.
A reference to a Boolean value. The block can set the value to YES to stop further processing of the array. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block.

Discussion of [NSArray enumerateObjectsUsingBlock]
If the Block parameter is nil this method will raise an exception.

NSArray enumerateObjectsUsingBlock example.
 NSMutableArray *myArray = [NSMutableArray arrayWithObjects:@"a", @"b", nil];
 [myArray enumerateObjectsUsingBlock:^(id anObject, NSUInteger idx, BOOL *stop) {
     // Attempt to mutate the array during enumeration
     [myArray addObject:@"c"];

Example of [NSArray enumerateObjectsUsingBlock].
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if( [obj isContagious] ){
        *stop = YES;    // Stop enumerating

    if( ![obj isKindOfClass:[Perefrigia class]] ){
        return;    // Skip this object

    [obj immanentizeTheEschaton];

NSArray enumerateObjectsUsingBlock example.
NSMutableArray *results = [NSMutableArray array];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
        if([obj isKindOfClass:[Elephant class]])
            [results addObject:obj];

End of NSArray enumerateObjectsUsingBlock example article.