Subject: Re: Strange cast for CFURLRef

On Mar 31, 2009, at 1:32 PM, Patrick Burleson wrote:

I ran into something I don't quite understand and was hoping to get
some enlightenment. There's a method defined on AudioPlayer that goes
like this:

- (id) initWithURL: (CFURLRef) fileURL;


The question I have is on the line:

AudioPlayer *thePlayer = [[AudioPlayer alloc] initWithURL: (NSURL *)fileURL];

Why does fileURL have to be cast to NSURL * when initWithURL wants a
CFURLRef? Without that cast, I get a compile error about incompatible

It appears the reason for the CFURLRef is that's what the lower level
Sound Toolbox calls need, but why all the casting at the higher levels
when it could just be a NSURL until the time when the toll free bridge
cast to CFURLRef is needed for those calls?

+alloc returns an untyped (`id`) object.

The compiler must consider all -initWithURL: methods that it has seen declared. Since the frameworks provide -initWithURL:(NSURL *)url (and the compiler doesn't know about the toll free bridging between NSURL and CFURL), the warning is generated.

You can cast the argument, as you have done above. You can also cast the result of +alloc:

AudioPlayer *thePlayer = [(AudioPlayer *)[AudioPlayer alloc] initWithURL: fileURL];

A better solution, though, is to avoid being in this situation in the first place.

-initWithFoo:(Foo *)foo

Avoid designing classes whose initializers which use identical names for different types.



Cocoa-dev mailing list (Cocoa-dev@xxxxxxxxxxxxxxx)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)

Help/Unsubscribe/Update your Subscription:

This email sent to maillists@xxxxxxxxx