views:

53

answers:

4

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?

+1  A: 

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.

quixoto
+2  A: 

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.

Lou Franco
You're right, the issue was with strPhone. I was nesting core foundation functions that were returning retained objects. Because they were nested, they weren't being released.
Jesse Bunch
One more thing, could you elaborate on the difference between using self.property = nil and [property release] ? Am wrong in assuming that they are equivalent?
Jesse Bunch
It's equivalent from a release perspective. If you subclass, they could have different behavior. Also, if you change the kind of property it is, the set to nil may no longer be appropriate. Finally, there are KVO features that I think are triggered by setting, but not by releasing (not sure about that though). http://developer.apple.com/mac/library/documentation/cocoa/conceptual/KeyValueObserving/KeyValueObserving.html -- basically, if you only care about releasing, the set to nil is equivalent.
Lou Franco
+1  A: 

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.

jojaba
+1  A: 

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

Wevah