Monday, June 17, 2013

NSIndexSet initWithIndexSet example in Objective C (iOS).


NSIndexSet initWithIndexSet

Initializes an allocated NSIndexSet object with an index set.

- (id)initWithIndexSet:(NSIndexSet *)indexSet

Parameters
indexSet
An index set.

Return Value
Initialized NSIndexSet object with indexSet.

Discussion of [NSIndexSet initWithIndexSet]
This method is a designated initializer for NSIndexSet.

NSIndexSet initWithIndexSet example.
NSMutableIndexSet *selectedRows = [[[NSMutableIndexSet alloc] initWithIndexSet:[_dataTableView selectedRowIndexes]] autorelease];
NSMutableIndexSet *rowsToDelete = [[selectedRows copy] autorelease];

Example of [NSIndexSet initWithIndexSet].
- (NSUInteger)indexForImageGivenIndexSet:(NSIndexSet*)indexSet             // Set of indexes you want to select from
                         prizeImageIndex:(NSUInteger)prizeIndex      // The prize index
                        probabilityScale:(CGFloat)probabilityScale   // The scale for the prize (8.0 for 8x less than the others)
{
    // If invalid, return what was given
    if (![indexSet containsIndex:prizeIndex]) {
        return prizeIndex;
    }

    // Calculate our probabilities
    // For a set of 4, with a scale of 8 on the prize, our probabilities would be
    // 0.04 (prize), 0.32, 0.32, 0.32
    double prizeProbability = (1.0 / indexSet.count) * (1.0 / probabilityScale);

    double val = (double)arc4random() / RAND_MAX;

    if (val < prizeProbability) {
        return prizeIndex;
    }
    else {
        // Select from the others in range equally
        NSMutableIndexSet* newSet = [[NSMutableIndexSet alloc] initWithIndexSet:indexSet];
        [newSet removeIndex:prizeIndex];

        NSInteger selectedPosition = arc4random() % newSet.count;
        __block NSInteger count = 0;
        return [newSet indexPassingTest:^BOOL(NSUInteger idx, BOOL *stop) {
            if (count == selectedPosition) {
                *stop = YES;
                return YES;
            }
            else {
                count++;
                return NO;
            }
        }];
    }
}

End of NSIndexSet initWithIndexSet example article.