Re: How to choose different implementations of an object method at runtime?
Re: How to choose different implementations of an object method at runtime?
- Subject: Re: How to choose different implementations of an object method at runtime?
- From: Ken Thomases <email@hidden>
- Date: Thu, 23 Jan 2014 10:35:55 -0600
On Jan 20, 2014, at 2:27 PM, Michael Crawford wrote:
> I'm working on a Mac OS X product that currently runs on 10.6 through to 10.9. This product includes an NSColor category method named CGColor, which is patterned after the iOS UIColor interface and returns a CGColorRef.
>
> @interface NSColor (CGColor)
> - (CGColorRef)CGColor CF_RETURNS_RETAINED;
> @end
>
> As I'm sure you are aware, 10.8 now defines a method that does the same thing using the same name. I'd like to make it so that calling code doesn't have to distinguish between these two methods but invokes the correct one based on which version of the runtime is present. What is the best approach to solving this problem?
1) Put the method into a category in a loadable bundle. Only load that bundle if ![NSColor instancesRespondToSelector:@selector(CGColor)].
2) Put the implementation in a function with the right signature for the IMP of that method. At runtime, if NSColor doesn't implement the method (as above), use the Objective-C runtime to add the method to the class with your function as the implementation.
static CGColorRef my_NSColor_CGColor_imp(id self, SEL _cmd)
{
// ...
}
Early in app start-up:
if (![NSColor instancesRespondToSelector:@selector(CGColor)])
class_addMethod([NSColor class], sel_registerName("CGColor"), (IMP)my_NSColor_CGColor_imp, "@@:");
> On Jan 23, 2014, at 4:02 AM, Greg Parker <email@hidden> wrote:
>
>> On Jan 20, 2014, at 12:27 PM, Michael Crawford <email@hidden> wrote:
>>> I also realize that the 10.8 version returns an autoreleased object whereas the version written a couple of years ago must have the resulting reference freed by the caller. I'm not sure how Apple pulls that off with a CF reference but I'd love to have a solution for that as well.
>>
>> The NS/CF bridge means that calling autorelease on a CF object works fine.
>
> Thanks for the reply, Greg. I running with ARC enabled. The compiler flags any calls to autorelease. What am I missing?
You can compile individual translation units with ARC disabled.
Regards,
Ken
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden