当前位置: 移动技术网 > IT编程>移动开发>IOS > CoreFoundation对象的内存管理

CoreFoundation对象的内存管理

2019年04月04日  | 移动技术网IT编程  | 我要评论

锐度紫梦,不用安装的游戏,香港蒲典

近来没什么新项目做,想学习一些swift开源项目,看了几个文件感觉有点懵,可能水平还没达到,等用到具体内容的时候再去仔细看吧。

关于现在的项目,想想单元测试还可以完善一下,就在framwork工程中写了一些测试用例。准备开始测试之前,先用product-analyze(快捷键cmd+shift+b)分析一下,发现有未释放的对象。

    cfuuidref uuidref = cfuuidcreate(kcfallocatordefault);
    nsstring *struuid = (nsstring *)cfbridgingrelease(cfuuidcreatestring(kcfallocatordefault,uuidref));
    nsdata *deviceid = [struuid datausingencoding:nsutf8stringencoding];
    cfrelease(uuidref);//potential leak of an object stored into 'uuidref'

原来是在创建uuid的方法中,没有释放uuidref这个cf对象,最后加上cfrelease就可以了。

但是在上面的第二行代码中,有cfbridgingrelease方法,表示把cf对象转换为oc对象,包括所有权转换,之后可以由arc自动释放对象。

再仔细看过后,发现原来上面的代码中其实有两个cf对象,把第二行中拆分成下面这样,其中__bridge可以把cf对象转为oc对象,不包括所有权转换,所以最后面有cfrelease释放stringref对象。

再次运行analyze,又报其它错误

    cfuuidref uuidref = cfuuidcreate(kcfallocatordefault);
    cfstringref stringref = cfuuidcreatestring(kcfallocatordefault,uuidref);
    nsstring *uuid = (__bridge nsstring *)stringref;
    nsdata *deviceid = [uuid datausingencoding:nsutf8stringencoding];
    cfrelease(uuidref);//potential leak of an object stored into 'uuidref'
    cfrelease(stringref);//reference-counted object is used after it is released

对象释放之后仍然有使用,创建对象,使用完毕后释放对象,很对的,难道什么地方写得不对吗?

在stackoverflow上找到,比较之后发现是需要重新拷贝一份uuid对象,因为在调用cfrelease之后,之前的uuid会被释放掉,再把之前的uuid作为函数返回值返回时,就会报错。

最后正确的写法改为

    //(nsstring *)cfbridgingrelease(stringref) 相当于__bridge__transfer把cf对象转成oc对象,所有权也由cf转到oc,arc下会自动释放
    //__bridge 只是把cf对象转为oc,不包含所有权的转换
    //cfbridgingretain(id) 相当于__bridge__retained把oc对象转为cf对象,所有权也由oc转到cf,需要手动释放
    cfuuidref uuidref = cfuuidcreate(kcfallocatordefault);
    cfstringref stringref = cfuuidcreatestring(kcfallocatordefault,uuidref);
    nsstring *uuid = [nsstring stringwithstring:(__bridge nsstring *)stringref];
    nsdata *deviceid = [uuid datausingencoding:nsutf8stringencoding];
    cfrelease(uuidref);//potential leak of an object stored into 'uuidref'
    cfrelease(stringref);//reference-counted object is used after it is released

 

 

看左侧的博客目录发现三月份竟然一篇都没有写,上个月是有点荒废了,事情有点多。之后尽量保持每月至少一篇技术博客,多学习一些东西,找到值得记录的内容。加油吧!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网