开发者

Cannot strip newline from Cocoa NSMutableString

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 wor开发者_运维知识库k... 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...


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.


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

NSString* trimmedString = [b64String stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];


You can trim newlines from a NSMutableString in-place, but you need to use the CFStringTrim method from Core Foundation.

Objective-C:

NSMutableString *string = [NSMutableString stringWithString:@"\nfoo bar baz\n"];
CFStringTrim((__bridge CFMutableStringRef)string, (__bridge CFStringRef)@"\n");

Swift:

let string = NSMutableString(string: "\nfoo bar baz\n")
CFStringTrim(string as CFMutableString, "\n" as CFString)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜