简体   繁体   中英

Objective-C memory leak when returning NSString

I want to be sure that my code is not leaking, since this small snippet is called thousand times in my app. I run the app through Instruments and the initWithBytes seems to be problematic. Is anything wrong in this code?

First [reader readString] is called.

case FirstCase:
{       
    NSString *string = [reader readString];
    [self setPropertyByName:propertyName value:string];
    break;
}
...

readString is returns the strings which is autoreleased.

- (NSString*) readString
 {
       ...
       NSString *string = [[[[NSString alloc] initWithBytes:cursor length:stringLength encoding:NSUTF8StringEncoding] autorelease];         
      return string;
}

Is the code OK? Any other better approach to avoid autorelease?

I cannot change my code to ARC. Plain old non-ARC memory management.

What you posted is OK. The only rule at this point is that methods contain "create" or "alloc" will return an object that needs to be explicitly released. In your case that is the string returned in the readString method.

Since the object will be returned you need to retain it till the end of the run loop cycle which the autorelease pool will do. What that means for instance is if this method will be called in a for loop the objects will not be deallocated before the loop has exited.

If you want or need to avoid that I suggest you to do the same pattern with "create" or "alloc" and return an object not being autoreleased:

case FirstCase:
{       
    NSString *string = [reader createReadString];
    [self setPropertyByName:propertyName value:string];
    [string release];
    break;
}
...


- (NSString*) createReadString
{
       ...
       NSString *string = [[[NSString alloc] initWithBytes:cursor length:stringLength encoding:NSUTF8StringEncoding];         
      return string;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM