通过Objective-C中的类别有条件地覆盖系统方法? [英] Conditionally overriding a system method via categories in Objective-C?

查看:163
本文介绍了通过Objective-C中的类别有条件地覆盖系统方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法提供一个方法实现(承载与框架定义的方法完全相同的名称)只有当该方法还没有在系统中定义?例如方法 [NSSomeClass someMethod:] 仅存在于Mac OS X 10.6中,如果我的应用程序在10.5中运行,我将在类别中提供该方法的定义。但是,当应用程序在10.6中运行时,我希望操作系统提供的方法运行。

Is there a way to provide a method implementation (that bears the exact same name of a method defined by the framework) only when the method isn't already defined in the system? For example method [NSSomeClass someMethod:] exists only in Mac OS X 10.6 and if my app runs in 10.5, I will provide that method's definition in a category. But when the app runs in 10.6, I want the OS-provided method to run.

背景: 10.5和10.6。问题是,我最近意识到方法 + [NSSortDescriptor sortDescriptorWithKey:ascending:] 仅存在于10.6中,我的代码已经被该方法调用。我可以为它提供一个默认实现(因为这一次它不是太难以自己实现),但我想要的原生的一个,当我的应用程序运行在10.6。此外,如果我在将来遇到类似的问题(使用更难以实现的方法),我可能无法避免提供一个单独的替换。

Background: I'm creating an app targeted for both 10.5 and 10.6. The problem is that I recently realized that method +[NSSortDescriptor sortDescriptorWithKey:ascending:] only exists in 10.6 and my code is already littered by that method call. I could provide a default implementation for it (since this time it's not too difficult to implement it myself), but I want the "native" one to be called whenever my app runs on 10.6. Furthermore if I encounter similar problems in the future (with more difficult-to-implement-myself methods), I might not be able to get away with providing a one-liner replacement.

这个问题类似于覆盖方法通过ObjC类和调用默认实现?,但是区别是我想提供实现只有当系统没有一个。

This question vaguely similar to Override a method via ObjC Category and call the default implementation? but the difference is that I want to provide implementations only when the system doesn't already have one.

谢谢。

推荐答案

是的,这是可能的。因为你的目标是10.5+我假设你使用ObjC2运行时,这使得它很简单。

Yes, this is possible. Since you are targetting 10.5+ I'm assuming you are using the ObjC2 runtime, which makes it fairly straightforward.

Objective-C运行时参考具有您需要的所有方法。具体来说,您可以使用class_getClassMethod或class_getInstanceMethod来查看方法是否已存在,然后使用class_addMethod将您的实现绑定到该选择器(如果该类还没有该选择器)。

The Objective-C Runtime Reference has all the methods you will need. Specifically, you can use class_getClassMethod or class_getInstanceMethod to see if the method already exists, and then class_addMethod to bind your implementation to that selector if the class doesn't already have it.

这篇关于通过Objective-C中的类别有条件地覆盖系统方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆