Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return CFDataRef without memory leak?[ios]

When I return a CFDataRef by

(CFDataRef)MyFunction{
    .....
    CFDataRef data = CFDataCreate(NULL, buf, bufLen);
    free(buf);
    return data;
}

There is a memory leak, how to make CFDataRef autorelease? the method [data autorelease] doesn't exit.

like image 516
user hhh Avatar asked Nov 21 '11 08:11

user hhh


2 Answers

You can't autorelease Core Foundation objects. (However, you can autorelease Core Foundation objects that support toll-free bridging such as CFDataRef; see @newacct's answer below.)

The Objective-C convention is to name your method such that it starts with the word new to indicate that the caller is responsible for releasing its return value. For example:

+ (CFDataRef)newDataRef {
    return CFDataCreate(...);
}

CFDataRef myDataRef = [self newDataRef];
...
CFRelease(myDataRef);

If you conform to this naming convention, the Xcode static analyzer will correctly flag Core Foundation memory managment issues.

like image 174
titaniumdecoy Avatar answered Nov 19 '22 20:11

titaniumdecoy


how to make CFDataRef autorelease? the method [data autorelease] doesn't exit.

Simply cast it to an object pointer type in order to call autorelease:

-(CFDataRef)MyFunction{
    .....
    CFDataRef data = CFDataCreate(NULL, buf, bufLen);
    free(buf);
    return (CFDataRef)[(id)data autorelease];
}
like image 37
newacct Avatar answered Nov 19 '22 18:11

newacct