views:

274

answers:

2

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...

+3  A: 

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.

KennyTM
Doesn't work - [b64String stringByReplacingOccurrencesOfString:@"\n" withString:@""]; NSLog(@"(%@)", b64String);The "\n" is still there ...
Mr-sk
@Mr-sk: See the update. Your `stringByTrimmingCharactersInSet:` has problem too, see the other answer.
KennyTM
+4  A: 

This is because the method stringByTrimmingCharactersInSet: returns a new string instead of modifying the current one.

NSString* trimmedString = [b64String stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
zneak
Doh! Thanks guys - should have slowed down a little to read. heh
Mr-sk