Monday, June 17, 2013

NSIndexSet enumerateIndexesWithOptions example in Objective C (iOS).


NSIndexSet enumerateIndexesWithOptions

Executes a given Block over the index set’s indexes, using the specified enumeration options.

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

Parameters of [NSIndexSet enumerateIndexesWithOptions]
opts
A bitmask that specifies the options for the enumeration (whether it should be performed concurrently and whether it should be performed in reverse order). See NSEnumerationOptions for the supported values.
block
The Block to apply to elements in the set.
The Block takes two arguments:
idx
The index of the object.
stop
A reference to a Boolean value. The block can set the value to YES to stop further processing of the set. The stop argument is an out-only argument. You should only ever set this Boolean to YES within the Block.

NSIndexSet enumerateIndexesWithOptions example.
-(IBAction)deleteThree:(id)sender {
    NSIndexSet *indxs = [self.view.subviews indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return [obj isKindOfClass:[UIImageView class]];
    }];

    __block int i = 0;
    [indxs enumerateIndexesWithOptions:NSEnumerationReverse usingBlock:^(NSUInteger idx, BOOL *stop) {
        [[self.view.subviews objectAtIndex:idx] removeFromSuperview];
        i++;
        if (i==3)
            *stop = YES;
    }];
}

Example of [NSIndexSet enumerateIndexesWithOptions].
#import <Foundation/Foundation.h>
enum {
    kMonday = 1 << 0,
    kTuesday = 1 << 1,
    kWednesday = 1 << 2,
    kThursday = 1 << 3,
    kFriday = 1 << 4,
    kSaturday = 1 << 5,
    kSunday = 1 << 6,
};
typedef int DayBits;

NSString * const shortDayNames[] = { @"Mon", @"Tues", @"Wed", @"Thurs", @"Fri", @"Sat", @"Sun" };
NSString * const fullDayNames[] = { @"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday", @"Sunday" };

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        // Demo all possible combinations
        for( DayBits days_as_bits = 0; days_as_bits < 128; days_as_bits++ ){
            // Create an index set from the bits
            NSMutableIndexSet * indexes = [NSMutableIndexSet indexSet];
            for( int bit = 0; bit < 7; bit++ ){
                if( days_as_bits & (1 << bit) ){
                    [indexes addIndex:bit];
                }
            }

            // Create string for result
            NSMutableString * daysDesc = [NSMutableString string];
            // Enumerate the index set backwards and build up the string
            __block BOOL contiguous = NO;
            [indexes enumerateIndexesWithOptions:NSEnumerationReverse
                                      usingBlock:^(NSUInteger idx, BOOL *stop) {
                // Use short names unless this is the name that will appear
                // at the end of the string
                NSString * const * dayNames = shortDayNames;
                if (0 == [daysDesc length]) {
                    dayNames = fullDayNames;
                }
                // If the previous index is present, we're working on a contiguous set
                if( [indexes containsIndex:(idx - 1)] ){
                    // If we were already in a contiguous set, just continue
                    if( contiguous ){
                        return;
                    }
                    // This is the end day of a contiguous set; place the name
                    // and a hyphen
                    else {
                        [daysDesc insertString:[NSString stringWithFormat:@"-%@", dayNames[idx]]
                                                                  atIndex:0];
                        contiguous = YES;
                        return;
                    }
                }
                // We've reached the start day of a set.
                // Turn off contiguous and fall through
                else {
                    contiguous = NO;
                }

                // Place a comma and today's name
                [daysDesc insertString:[NSString stringWithFormat:@", %@", dayNames[idx]]
                                                          atIndex:0];
            }];
            // Clean up extraneous comma and space at the beginning of the string
            daysDesc = [daysDesc stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" ,"]];
            NSLog(@"%d: %@", days_as_bits, daysDesc);
        }

    }
    return 0;
}

End of NSIndexSet enumerateIndexesWithOptions example article.