Sunday, June 2, 2013

NSMutableString stringWithCapacity example in Objective C (iOS).


NSMutableString stringWithCapacity

Returns an empty NSMutableString object with initial storage for a given number of characters.

+ (id)stringWithCapacity:(NSUInteger)capacity

Parameters
capacity
The number of characters the string is expected to initially contain.

Return Value
An empty NSMutableString object with initial storage for capacity characters.

Discussion of [NSMutableString stringWithCapacity]
The number of characters indicated by capacity is simply a hint to increase the efficiency of data storage. The value does not limit the length of the string.

NSMutableString stringWithCapacity example.
NSMutableString *newPath = [NSMutableString stringWithCapacity:42];
OR

NSMutableString *newPath = [[NSMutableString alloc] init];

I see a lot a declarations written on two lines (i.e.)

NSMutableString *newPath;
newPath = [NSMutableString stringWithCapacity:42];

Example of [NSMutableString stringWithCapacity].
-(NSString *) randomizeHint:(NSString *) wordToShuffle{

    NSMutableString * outputstring = [NSMutableString stringWithCapacity:[wordToShuffle length]];
    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]];
        [outputstring appendFormat:@"%c",[wordToShuffle characterAtIndex:randomnum]];
    }

    CCLOG(@"outputstring is:%@",outputstring);
    return outputstring;

 }

NSMutableString stringWithCapacity example.
NSMutableString* message = [NSMutableString stringWithCapacity:15];
[message setString:@"This is spinach"];

BOOL boolA = YES, boolB = NO, boolC = YES;

// add "and" if there are any fruits
if(boolA || boolB || boolC)
    [message appendString:@" and"];

if(boolA)
    [message appendString:@" apples,"];
if(boolB)
    [message appendString:@" oranges,"];
if(boolC)
    [message appendString:@" mangoes,"];

// remove last ","
if(boolA || boolB || boolC)
[message deleteCharactersInRange:NSMakeRange([message length] - 1, 1)];

End of NSMutableString stringWithCapacity example article.