Potential Leaked Object Error - iphone

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?

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.

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.

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.

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

Related

Usage of NSMutableString vs NSString?

I am confused between NSString and NSMutable string usage.
Suppose I have instance variables one and two declared in class like this:
NSString *one;
NSMutableString *two;
let us suppose I have created setters and getters of them using properties.
lets say I have changed my "two" string like these:
1. [two appendString:#"more string"];
2. two = #"string"
3. self.two = #"string"
Questions:
would 1st line release previous string and allocate new object and assign value to it.
if yes, then does that mean creating getters and setters are unnecessary in this case ? OR its unnecessary to create properties in NSMutablestring
In this case would the previous allocated string object released ?
Its for sure that first object would be released as we are calling setters here. is this code necessary or we can just use the code line 2 to assign string.
Now about NSString:
As can modify the string like this also :
one = [one stringByAppendingString:#" more string"];
self.one = [one stringByAppendingString:#" more string"];
Which is better using NSMutablestring or NSString ?
Sorry for long post, but I needed to understand these concepts.
For the first part of your question:
Almost definitely not. I expect the memory will be allocated dynamically, rather than released and reallocated.
If the previous answer is no, this is also, no.
The second and third options don't even work with the warning Incompatible pointer types assigning NSMutableString to NSString
I expect NSMutableString will be slightly more efficient in terms of memory as you are indicating early on that the program may need memory dynamically. NSString is likely to be allocated a single, suitably sized block of memory.
Your views of NSMutableString seem to be what the stringBy.. methods of NSString will do:
With NSString and its stringBy... methods, you are creating new objects, releasing the old one (if need be) and making the new object autorelease. (Take care if you are changing from non-autorelease to autorelease, you may have a release in your dealloc that isn't needed anymore)
NSString is a not mutable string object, which means, after initialization, you cannot change it, NSMutableString is mutable meaning you can append another string to it or other modifications.
when you do [two appendString:#"more string"], the pointer still pointed to the same location in memory and you don't have to worry about allocation or deallocation.
When you do two = #"string" , it means you make your string pointer pointed to a specific location in memory which contains static string with value "string" inside.
When you do self.two = #"string", you've already have a property named two declared. By using property in xcode, you don't have to worry about the memory since you've already specified in your property declaration. It is a nice tool xcode provide to you, and you should definitely use it whenever you can.
NSMutableString will save some memory as NSString objects are always constants. So reassigning a new value to an NSString variable will allocate new memory for the new string.
However, please note a few errors in your code. You will have to initialize the objects before sending messages to them:
// this won't work
NSString *one;
[one stringByAppendingString:#"more string"];
// nor this
NSMutableString *two;
[two appendString:#"more string"];
// first do this:
NSString *one = #"an initial string constant"; // or
NSString *one = [NSString string];
NSMutableString *two = [NSMutableString string];
NSString objects are immutable this means that when you "modify" a NSString you are in fact creating a new string and not modifying the old which is not very effective. With NSMutableString the string is kept in a buffer than can be modified.
So the simple rule is that if you need to modify the string in any way use a NSMutableString and if not NSString. You can also cast a NSMutableString to a NSString but not the other way around (then you need to make a copy)

retainCount shows MaxInt

After trying to print retainCount of object I get 2147483647. Why do I get such a result? It should be 1, shouldn't?
NSString *myStr = [NSString new];
NSUInteger retCount = [myStr retainCount];
NSLog(#"refCount = %u", retCount);
2011-09-08 17:59:18.759 Test[51972:207] refCount = 2147483647
I use XCode Version 4.1. Tried compilers GCC 4.2 and LLVM GCC 4.2 - the same result.
Garbage Collection option was set to unsupported.
NSString is somewhat special when it comes to memory management. String literals (something like #"foo") are effectively singletons, every string with the same content is the same object because it can't be modified anyway. As [NSString new] always creates an empty string that cannot be modified, you'll always get the same instance which cannot be released (thus the high retainCount).
Try this snippet:
NSString *string1 = [NSString new];
NSString *string2 = [NSString new];
NSLog(#"Memory address of string1: %p", string1);
NSLog(#"Memory address of string2: %p", string2);
You'll see that both strings have the same memory address and are therefore the same object.
This doesn't directly answer your question, but retainCount is not really all that useful and should not be used for testing. See this SO post for details.
When to use -retainCount?
While NSString's are an odd case (there are others in the framework) you might also run across this in other clases - it's one of the ways of creating a singleton object.
A singleton only exists once in the app and it's pretty important that it never gets released! Therefore, it will overwrite some methods of NSObject including (but not limited to):
- (id)release {
// Ignore the release!
return self;
}
- (NSUInteger)retainCount {
// We are never going to be released
return UINT_MAX;
}
This object can never be released and tells the framework that it's a singleton by having a ludicrously high retain count.
Checkout this link for more information about singleton objects.
I've seen this a couple of times regarding NSStrings, the retainCount returns the maximum count instead of the actual one when you try to look at retainCounts of strings in this manner.
Try this;
NSString *myStr = [[NSString alloc] init];
NSUInteger retCount = [myStr retainCount];
NSLog(#"refCount = %u", retCount);
Edit: Restored NSUInteger

iphone/ipad memory leak from NSString assigned to itself

I have two leaks shown by the instruments tool. I have looked around on google but I haven't seen exactly my problem on there.
Problem #1:
self.wallText = [[text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
I have tried various configurations of the above line but all leak. I need to do both those trimming operations. 'text' is declared with either #"" or stringWithFormat.
My other issue is with the following line:
NSString * value = [elements objectAtIndex:i+1];
if ([value length] >= 2 && [[value substringToIndex:2] isEqualToString:#"S_"]){
value = [value substringFromIndex:2]; // LEAK HERE
}
I need to get all of the string except for the first 2 characters so I don't know how I could release it first or something... if that is indeed what I should be doing.
I could get away wtih leaks before with previous projects but this one is very memory intensive and I need all the memory I can get!
Any pointers would be greatly appreciated
Did you declare #property (retain) for wallText, did you do [wallText release] in dealloc method?
Double check above things and you will not have leaks any more
For Updated Part:
It is really strange that you have a memory leak there. Because at first, your value points to an autoreleased object then it points to another autoreleased object which I think is fine.
have u use alloc for value. value = [value substringFromIndex:2]; .here now value is referencing to new autorelease string. so u can not release previous object.

NSString *string = #"someString" vs NSString *string = [[NSString alloc] initWithFormat#"%#", string]

If I have a method
- (void) myMethod:(NSString *)string {
[Object anothermethodWithString:string];
}
and I call
[Object myMethod:#"this is a string with no alloc statement"]
Do I need to do something like
- (void) myMethod:(NSString *)string {
NSString *string2 = [[NSString alloc] initWithFormat:#"%#", string];
[Object anothermethodWithString:string2];
[string2 release];
}
instead of the way I had myMethod before? I have misbehaving code that seems to be caused by a string being auto-released while a second method within another method is being called (like in the example). The second way I have myMethod fixed all of my problems.
So is a "non-alloc" string an auto-released string? I asked this question as a follow up to another question (which was completely unrelated and is why I am creating this post), and a few sources said that I don't need to reallocate the string. I am confused, because the behavior of my code tells me otherwise.
Dave's got it right. You only need to worry about calling release on objects that you new, alloc, retain, or copy.
The above rule works very well, but if you're curious and want to get into a lot of detail, I suggest reading the Memory management Programming Guide from Apple's docs. It's free and goes from basic concepts into a lot of details.
If you use : NSString *str = #"". It is kind of a constant, you don't need to do any memory management.
If you call from a method : NSString *str = [NSString stringWithFormat:#""], the str is already autoreleased.
If you manually alloc, init. You need to call release, or autorelease yourself.
The general memory convention is : if you do something with new, alloc, retain, or copy, you need to release it yourself, any other cases, the object is autoreleased, don't release it

Best way to initialise / clear a string variable cocoa

I have a routine that parses text via a loop. At the end of each record I need to clear my string variables but I read that someString = #"" actually just points to a new string & causes a memory leak.
What is the best way to handle this? Should I rather use mutable string vars and use setString:#"" between iterations?
You have to be careful in which case you create the NSString: (factory method) or (alloc init or (using #"").
If you use #"", it is a constant string, see here: Constant NSString
If you use [[NSString alloc] init], you need to release it.You just need to do [someString release].
If you use something like [NSString stringWithFormat:#""], you don't need to release it because it is already auto released by runtime
Since NSStrings are immutable, you cannot change the contents of the string. And by initializing it with #"" you're actually creating a constant NSString object.
You can either work with a NSString local to the loop, and release it in the end of the loop - or you can use a NSMutableString instead. I would prefer the loop local string though.
for ( ; ;) {
NSString* str = [[NSString alloc] initWithFormat:#"%#", CONTENT];
...
[str release];
}