Jesse Bunch
Jesse Bunch

Reputation: 6679

Potential Leaked Object Error

I'm getting a potentially leaked object error from the Static Analyzer for this line:

strCleanPhone = [[[[strPhone stringByReplacingOccurrencesOfString:@" " withString:@""] 
                           stringByReplacingOccurrencesOfString:@"(" withString:@""] 
                          stringByReplacingOccurrencesOfString:@")" withString:@""] 
                         stringByReplacingOccurrencesOfString:@"-" withString:@""];

For one, is this the preferred way to strip non-numeric characters from a phone number string?

Two, can you possibly explain why this would be a leaked object?

Upvotes: 0

Views: 177

Answers (4)

Wevah
Wevah

Reputation: 28242

Make sure you expand the analyzer warning by clicking the warning text in the source view! Chances are it's pointing to where a variable is last referenced; if you expand the warning you'll see a bunch of arrows indicating code flow, which will help indicate where you've allocated your potentially-leaked object.

(tl;dr: Post more code.)

Upvotes: 1

tidwall
tidwall

Reputation: 6949

If you are looking to strip out characters that are not numbers.

NSString *strPhone = @"(555) 444-3333";
NSMutableString *strCleanPhone = [NSMutableString string];
for (int i=0;i<[str length];i++)
{
    unichar ch = [str characterAtIndex:i];
    if (isnumber(ch)) [strCleanPhone appendFormat:@"%c", ch];
}

But I suggest looking into regular expressions.

Upvotes: 1

Lou Franco
Lou Franco

Reputation: 89242

The strings created by stringByReplacingOccurrencesOfString are autoreleased, so they aren't leaked. If there's a leak, it has to do with strPhone and strCleanPhone.

For example, if strCleanPhone is a @property with the retain option, and is currently not nil, then your code leaks it. To use the release/retain code that was generated by synthesize you have to use the property syntax: self.strCleanPhone = .... Using just strCleanPhone = ... sets the instance variable and doesn't release any object it was pointing to.

Upvotes: 2

Ben Zotto
Ben Zotto

Reputation: 71058

If you're on iOS 4.0+, you might be able to use the new NSRegularExpression object to do this a little more elegantly.

The code you have as posted doesn't leak. It just creates four autoreleased string objects.

Upvotes: 1

Related Questions