How to return CFDataRef without memory leak?[ios]

丶灬走出姿态 提交于 2019-12-12 14:25:33

问题


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.


回答1:


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.




回答2:


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];
}


来源:https://stackoverflow.com/questions/8208917/how-to-return-cfdataref-without-memory-leakios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!