开发者

NSString stringByReplacingOccurrencesOfString leak

I am g开发者_JS百科etting NSCFString for the code below:

NSString *urlString;

/*  leak showing below line */

urlString = [urlString stringByReplacingOccurrencesOfString:@"\n" withString:@""];

How do you solve this leak?


You should do pointer allocation of string instead of static allocation. Change:

NSString urlString;

to:

NSString *urlString;

Also there seems to be some other code that initiates the urlString to some value to which you're doing the replace operation.


Most likely you created your urlString using +alloc/initWith.... If that's the case then you own the urlString reference and are responsible for releasing it at some point. However, when you get to the line you pasted in the question, you're overwriting the urlString reference with a new string reference, since stringByReplacingOccurrencesOfString:withString: returns a new string object (ie, it doesn't modify the string in place).

My recommendation would be to use an NSMutableString instead, which does allow in-place string manipulation.


it's from one my code is do all you want, i replaced to white space but you can replace to empty string (@"")

    NSString  * str_aLine;
    str_aLine = @"sometext \n and \t     and on";
    // replace tabs to space
    str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@"\t" withString:@" "];
    // replace \n to space
    str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
    // replace \r to space
    str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@"\r" withString:@" "];
    // reduce spaces to one space
    str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@" +" withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, str_aLine.length)];
    // trim begin and end from white spaces
    str_aLine = [str_aLine stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜