stringWithString leaking memory
Hi I have a simple function that basically returns a trimmed version of an input string. The problem is when I run instruments & check for lea开发者_如何转开发ks this functions shows 100% leaking specifically on line stringWithString.
Can anyone please guide me what am I doing wrong here.
+ (NSString *) trim:(NSString *)string
{
if (string == nil)
return nil;
NSString *str = [NSString stringWithString:string];
str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//[[NSString stringWithString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]] autorelease];
return str;
}
If this code is running on a thread, make sure that you have an autoreleasepool set up. The stringWithString returns an autoreleased object, and that can only happen when there is an autoreleasepool for your thread.
First, this looks absolutely fine to me, are you sure that the leak is with stringWithString:
?
Then, you don't need it anyway. You can simply do:
+ (NSString *) trim:(NSString *)string
{
if (string == nil)
return nil;
return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
The only reason I could think of is if you run this code from a spawn thread that doesn't have a NSAutoReleasePool, because [NSString stringWithString:string];
has an autorelease
message sent to it.
精彩评论