Monday, June 17, 2013

NSIndexSet enumerateIndexesUsingBlock example in Objective C (iOS).

NSIndexSet enumerateIndexesUsingBlock

Executes a given Block using each object in the index set.

- (void)enumerateIndexesUsingBlock:(void (^)(NSUInteger idx, BOOL *stop))block

Parameters of [NSIndexSet enumerateIndexesUsingBlock]
The Block to apply to elements in the set.
The Block takes two arguments:
The index of the object.
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 enumerateIndexesUsingBlock example.
In OS X 10.6 and later, you can use the -enumerateIndexesUsingBlock: message:

NSIndexSet *idxSet = ...

[idxSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
  //... do something with idx
  // *stop = YES; to stop iteration early

Example of [NSIndexSet enumerateIndexesUsingBlock].
This seems easy enough. Enumerate the index set using enumerateIndexesUsingBlock: and stick each index into an NSIndexPath object:

NSMutableArray * paths = [NSMutableArray array];
[indexes enumerateIndexesUsingBlock:^(NSUInteger index, BOOL *stop) {
        [paths addObject:[NSIndexPath indexPathWithIndex:index]];
[self.tableView insertRowsAtIndexPaths:paths
If your table view has sections, it's only a bit more complicated, because you'll need to get the correct section number, and specify it in the index path:

NSUInteger sectionAndRow[2] = {sectionNumber, index};
[NSIndexPath indexPathWithIndexes:sectionAndRow

NSIndexSet enumerateIndexesUsingBlock example.
-(NSMutableArray *)lookupAll: (NSString *)theName
    NSMutableArray *matches=[NSMutableArray array];
    NSIndexSet *result = [book indexesOfObjectsPassingTest: ^(id obj, NSUInteger idx, BOOL *stop)
                              if([[obj name] caseInsensitiveCompare: theName] == NSOrderedSame)
                                  return YES;
                                  return NO;
    [result enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        [matches addObject:[book objectAtIndex:idx]];
    return matches;

End of NSIndexSet enumerateIndexesUsingBlock example article.