Madan Mohan
Madan Mohan

Reputation: 8820

NSString stringByReplacingOccurrencesOfString leak

I am getting NSCFString for the code below:

NSString *urlString;

/*  leak showing below line */

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

How do you solve this leak?

Upvotes: 2

Views: 3940

Answers (3)

Kosar
Kosar

Reputation: 190

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]];

Upvotes: 0

Eimantas
Eimantas

Reputation: 49354

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.

Upvotes: 1

Dave DeLong
Dave DeLong

Reputation: 243156

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.

Upvotes: 0

Related Questions