Friday, June 21, 2013

NSMutableSet setWithCapacity example in Objective C (iOS).

NSMutableSet setWithCapacity

Creates and returns a mutable set with a given initial capacity.

+ (id)setWithCapacity:(NSUInteger)numItems

Parameters of [NSMutableSet setWithCapacity]
The initial capacity of the new set.

Return Value
A mutable set with initial capacity to hold numItems members.

Discussion of [NSMutableSet setWithCapacity]
Mutable sets allocate additional memory as needed, so numItems simply establishes the object’s initial capacity.

NSMutableSet setWithCapacity example.
-(NSString *) randomizeHint:(NSString *) wordToShuffle{

    NSString * outputstring = @"";

    NSMutableSet * usedNumberSet = [NSMutableSet setWithCapacity:[wordToShuffle length]];

    for (int i=0; i<[wordToShuffle length]; i++) {
        int randomnum = arc4random()%[wordToShuffle length];

        while ([usedNumberSet containsObject:[NSNumber numberWithInt:randomnum]]==YES) {
            randomnum = arc4random()%[wordToShuffle length];

        [usedNumberSet addObject:[NSNumber numberWithInt:randomnum]];

        // just set outputstring like so... no need to worry about a leaky mutable string then
        outputstring = [outputstring stringByAppendingFormat:@"%c",
                    [wordToShuffle characterAtIndex:randomnum]];

    return outputstring;


Example of [NSMutableSet setWithCapacity].
You probably want

NSMutableSet *set = [[NSMutableSet alloc] initWithCapacity: someNumber];

NSMutableSet *set = [NSMutableSet setWithCapacity: someNumber];

NSMutableSet setWithCapacity example.
NSMutableSet *randomCards = [NSMutableSet setWithCapacity:10];

[randomCards addObjectsFromArray:whiteListArray];

while ([randomCards count] < 10) {
    NSNumber *randomNumber = [NSNumber numberWithInt:(arc4random() % [randoms count])];
    [randomCards addObject:[randoms objectAtIndex:[randomNumber intValue]]];

End of NSMutableSet setWithCapacity example article.