CFStringRef to NSString ARC leaking. Why?

孤人 提交于 2019-12-11 09:56:50

问题


I have been looking around for the correct way to go from CFStringRef to NSString in ARC to avoid memory leaks and some of the main voted answers suggest:

NSString * string = (__bridge NSString *)cfString;

I am using that approach here but when profiling the app I still get a memory leak in this small method [see attached image].

So, I am not sure how to fix this. Anybody has the solution to this problem?

Thank you

So, apparently adding the CFRelease(ext) before the return fixed the leak. Problem is I don't think I fully understand the reason. I thought that the line:

NSString * extension = (__bridge NSString*)ext

Would take ownership of the Core Foundation ext string and handle the release. Can anybody explain what is going on here exactly?


回答1:


As per the de-facto "standard" Cocoa naming convention, functions that contain Create or Copy in their name return an object with a reference count of 1. You have to transfer this reference count into ARC-land so that ARC can take care of it. You use the __bridge_transfer keyword for this purpose.

NSString *string = (__bridge_transfer NSString *)cfString;



回答2:


Release the ext object or use __bridge_transfer.

Let me explain this a bit in the way I understand it:

  • __bridge – Normal casting. The retain count of casted object is partially managed by ARC and partially manually. You need to release the existing ownership on the CF side.

  • __bridge_transfer – “Converts CF object to NS object.” The retain count of casted object is fully managed by ARC. Existing ownership on the CF side is disposed for you.



来源:https://stackoverflow.com/questions/17967515/cfstringref-to-nsstring-arc-leaking-why

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