Friday, May 31, 2013

NSArray enumerateObjectsWithOptions usingBlock example in Objective C (iOS).


NSArray enumerateObjectsWithOptions usingBlock

Executes a given block using each object in the array.

- (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block

Parameters of [NSArray enumerateObjectsWithOptions usingBlock]
opts
A bit mask that specifies the options for the enumeration (whether it should be performed concurrently and whether it should be performed in reverse order).
block
The block to apply to elements in the array.
The block takes three arguments:
obj
The element in the array.
idx
The index of the element in the array.
stop
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 enumerateObjectsWithOptions usingBlock]
By default, the enumeration starts with the first object and continues serially through the array to the last object. You can specify NSEnumerationConcurrent and/or NSEnumerationReverse as enumeration options to modify this behavior.

NSArray enumerateObjectsWithOptions usingBlock example.
NSMutableArray *array = [[rows objectForKey:self.company.coaTypeCode] objectForKey:statementType];
[[array copy] enumerateObjectsWithOptions: NSEnumerationReverse
    usingBlock:^(id coaItem, NSUInteger idx, BOOL *stop) {
    if ([self objectIsTooUglyToExist:coaItem])
        [array removeObjectAtIndex:idx];
}]

Example of [NSArray enumerateObjectsWithOptions usingBlock].
NSMutableArray *newArray = [[NSMutableArray alloc] initWithCapacity:[myArray count]];
__block newArray;
[myArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

 double aValue = [obj doubleValue];                     
 aValue += 90.0;
 [newArray insertObject:[NSNumber numberWithDouble:aValue] atIndex:idx];
}];

NSArray enumerateObjectsWithOptions usingBlock example.
[myArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
    double aValue = [obj doubleValue];                     
    aValue += 90.0;
    [myArray replaceObjectAtIndex:idx withObject:[NSNumber numberWithDouble:aValue]];
}];

End of NSArray enumerateObjectsWithOptions usingBlock example article.