Monday, June 17, 2013

NSIndexSet initWithIndex example in Objective C (iOS).


NSIndexSet initWithIndex

Initializes an allocated NSIndexSet object with an index.

- (id)initWithIndex:(NSUInteger)index

Parameters
index
An index.

Return Value of [NSIndexSet initWithIndex]
Initialized NSIndexSet object with index.

NSIndexSet initWithIndex example.
NSIndexSet *indexes = [[NSIndexSet alloc] initWithIndex:rowToHighlight];
[myTableView selectRowIndexes:indexes byExtendingSelection:NO];
[indexes release];

Example of [NSIndexSet initWithIndex].
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
   atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
  newIndexPath:(NSIndexPath *)newIndexPath
{

  ChannelPageViewController *currentPageController, *destinationPageController;

  NSIndexSet * indices = [[NSIndexSet alloc] initWithIndex: indexPath.row];
  NSIndexSet *newIndices = [[NSIndexSet alloc] initWithIndex:newIndexPath.row];

  switch(type) {
      case NSFetchedResultsChangeInsert:
        [gridView insertItemsAtIndices:newIndices withAnimation:AQGridViewItemAnimationNone];
      break;

      case NSFetchedResultsChangeDelete:
        [gridView deleteItemsAtIndices:indices withAnimation:AQGridViewItemAnimationNone];
        break;

      case NSFetchedResultsChangeUpdate:
        [gridView reloadItemsAtIndices:indices withAnimation:AQGridViewItemAnimationNone];
        break;

      case NSFetchedResultsChangeMove:
        [gridView deleteItemsAtIndices:indices withAnimation:AQGridViewItemAnimationNone];
        [gridView insertItemsAtIndices:newIndices withAnimation:AQGridViewItemAnimationNone];
        break;
   }
}

NSIndexSet initWithIndex example.
dispatch_async(dispatch_get_main_queue(), ^{
                // RUN AFTER SEARCH HAS FINISHED
                [self.collectionView performBatchUpdates:^{
                    NSMutableArray *indexPaths = [NSMutableArray new];
                    NSInteger section = self.searches.count - 1;
                    [self.collectionView insertSections:[[NSIndexSet alloc] initWithIndex:section]];
                    for (NSInteger i = 0; i < results.count; i++) {
                        [indexPaths addObject:[NSIndexPath indexPathForItem:i inSection:section]];
                    }
                    [self.collectionView insertItemsAtIndexPaths:indexPaths];
                } completion:nil];
   });

End of NSIndexSet initWithIndex example article.