简体   繁体   中英

Potential memory leak in NSData category

When using the XCode analyzer I get a message saying:

Potential leak of an object allocated

The code this is in my NSData(String) category, the code is:

- (NSString*) utf8String
{
    return [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
}

Now how can I solve this? When I change the statement to:

- (NSString*) utf8String
{
    return [[[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding] autorelease];
}

My application crashes on the line where I call utf8String .

The cocoa naming conventions suggest that all methods return autoreleased objects, with the exception of methods whose names start with 'init', 'copy' or 'new'. The static analyzer knows and checks this.

You have two choices. You can rename the method to -newUTF8String, or you can return an autorelease object and retain it when you want to store the return value of this method.

I would prefer the latter, but both would be valid code.

I guess your application crashes because the variable is released before it is used. It is recommended to call retain if you do not use the return value right away but store it in a member variable.

...
myMemberVariable = [something utf8String];
[myMemberVariable retain];
...

To make sure that you do not produce a memory leak you have to release the member variable somewhere. A good place for that would be dealloc .

- (void)dealloc {
    if (myMemberVariable) [myMemberVariable release];

    [super dealloc];
}

I would also recommend having a look at Advanced Memory Management Programming Guide to get some detailed information about memory management of iOS.

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