How to return CFDataRef without memory leak?[ios]
Asked Answered
V

2

5

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.

Viscount answered 21/11, 2011 at 8:10 Comment(0)
P
8

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.

Pileup answered 21/11, 2011 at 8:14 Comment(3)
thanks ,I rename the MyFunciotn to newMyFunction,the warnings are gone!Viscount
Not true. You can autorelease Core Foundation objects. developer.apple.com/library/ios/#documentation/General/… "Note from the example that the memory management functions and methods are also interchangeable—you can use CFRelease with a Cocoa object and release and autorelease with a Core Foundation object."Frivolity
@newacct: That is only true for specific Core Foundation objects that support toll-free bridging. CFDataRef does support toll-free bridging, so in this particular case you are correct.Pileup
F
3

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];
}
Frivolity answered 26/9, 2012 at 6:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.