Nick
Nick

Reputation: 628

How to copy a NSURL object to an array of CFURL structs

I have an ivar that is a 'plain' C array of CFURLRef structs. I call this sourceURLArray. I initialize it to hold six elements.

Later on, in a function, I create (alloc/init) an NSURL* object. I call it fileURL and I want to save a copy of that object into the first element of the aforementioned array. I thought all I needed to do was this:

        sourceURLArray[0] = (__bridge CFURLRef)([fileURL copy]);

However when I execute the code I get message sent to deallocated instance messages the second time through the function. Upon inspection of the variables, after the line above executes, sourceURLArray[0] holds the same address as fileURL. Since fileURL goes out of scope when the function completes the address in sourceURLArray[0] is deallocated.

It seems I'm misunderstanding something fundamental about either copying, nuances with toll-free bridging, or both.

Upvotes: 0

Views: 356

Answers (1)

rmaddy
rmaddy

Reputation: 318774

Try:

sourceURLArray[0] = (__bridge_retained CFURLRef)([fileURL copy]);

or:

sourceURLArray[0] = (CFURLRef)CFBridgingRetain([fileURL copy]);

This tells ARC that you are transferring ownership to the other array. You must now properly call CFRelease on the CFURLRef at some point.

Upvotes: 1

Related Questions