How to Convert NSURL to CFURLRef
Asked Answered
Z

1

6

Apple gives sample code for Creating PDF document. But It uses CFURLRef

NSPanel savepanel gives NSURL.

I can't convert NSURL to CFURLRef

 path = CFStringCreateWithCString (NULL, filename, kCFStringEncodingUTF8);

 url = CFURLCreateWithFileSystemPath (NULL, path, kCFURLPOSIXPathStyle, 0);
 NSLog(@"CFURLRef %@",url);

output is

2016-04-22 00:34:26.648 XXX Analysis[12242:813106] CFURLRef AnalysisReport.pdf -- file:///Users/xxxxxx/Library/Containers/com.xxxxxx.xxxnalysis/Data/

convert code which i find

url = (__bridge CFURLRef)theFile;
NSLog(@"NSURL %@",url);

output is

2016-04-22 00:37:20.494 XXX Analysis[12325:816505] NSURL file:///Users/xxxxxx/Documents/xxxnalysis.pdf

at the end PDF file is saved but Program crash when the NSPanel closed.

Zest answered 21/4, 2016 at 21:45 Comment(2)
how does the crash looks like? Any errors in sandboxing log?Lahdidah
I found my answer. if you don't create CFStringRef with CFStringCreateWithCString . You dont need to call CFRelease(url);Zest
R
13

CFURLRef and NSURL are toll-free bridged. So typically, you would just do this:

NSURL *url = ...;
CFURLRef cfurl = CFBridgingRetain(url);

And when you no longer need the CFURL object:

CFRelease(cfurl);

Or if you're reasonably certain that the NSURL will stick around long enough, you can just do

CFURLRef cfurl = (__bridge CFURLRef)url;

If you're getting a crash, that probably means you're over-releasing something — specifically, that you're releasing an object that you don't own. I would suggest reading Apple's docs on object ownership:

https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html

Renoir answered 18/5, 2016 at 22:31 Comment(3)
How would I do this in Swift? Using CFBridgingRetain causes a runtime error and using (__bridge CFURLRef) causes a coding error.Bahner
Apparently, in Swift, those types are already bridged to native objects, so you should presumably just be able to cast it. See en.swifter.tips/toll-freeRenoir
I've tried that. It doesn't work, but I found a simpler way around what I wanted to do. Thank you.Bahner

© 2022 - 2024 — McMap. All rights reserved.