R – Cannot strip newline from Cocoa NSMutableString

cocoanewlinensmutablestringnsstringobjective c

Hey, for the life of me, this is not working:..

NSMutableString *b64String = [[[NSMutableString alloc] initWithFormat:@"Basic %@", [string _base64Encoding:string]] autorelease];

    [b64String stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    NSLog(@"(%@)", b64String);

    NSRange foundRange = [b64String rangeOfString:@"\n"];
    if (foundRange.location != NSNotFound)
        [b64String stringByReplacingOccurrencesOfString:@"\n"
                                            withString:@""
                                               options:0 
                                                 range:foundRange];
    NSLog(@"(%@)", b64String);

Both those methods I found on SO – and they don't seem to work… I've got to be doing something terribly wrong. But, if I break on the NSLog's, I can clearly see the "\n" in the string (in the debugger AND in the console out)

Also, this is true:

if (foundRange.location != NSNotFound)

And I can see if execute the stringByReplacingOccurencesOfString method…

Best Answer

Simply call

b64String = [b64String stringByReplacingOccurrencesOfString:@"\n" withString:@""]

is enough (remember to -release unnecessary copies of b64string. You may want to store it into another variable), or use the actual mutable method with full range:

[b64String replaceOccurrencesOfString:@"\n" withString:@"" options:0 range:NSMakeRange(0, [b64String length])];

In -stringByReplacingOccurrencesOfString:withString:options:range:, the range parameter specifies the range where the replacement occurs. That means nothing will get replaced outside of the range. In your code, you pass the range of the 1st appearance of \n. The effect is only 1 occurrence of \n will be removed.

The stringBy... methods are for immutable strings. They will not modify the input string. Instead, they create a copy of the immutable string and return the modified copy.