简体   繁体   English

是否可以拥有仅在方法尚不存在时才加载的Objective-C类别?

[英]Is it possible to have an Objective-C Category that is only loaded if the method doesn't already exist?

On a past project (pre-iOS 4.0), I wrote the following category method on NSSortDescriptor : 在过去的项目(iOS 4.0之前),我在NSSortDescriptor上编写了以下类别方法:

+ (id)sortDescriptorWithKey:(NSString *)key ascending:(BOOL)ascending;

When Apple released the iOS SDK 4.0, it included the exact same method (which presumably does exactly the same thing). 当Apple发布iOS SDK 4.0时,它包含了完全相同的方法(可能完全相同)。 Is it possible to write a category that is only added to the runtime either if you're running a particular OS version, or probably more to the point, if there isn't already a method declared with the same signature? 是否可以编写一个仅在运行特定操作系统版本时才添加到运行时的类别,或者如果还没有使用相同签名声明的方法,则可能更多?

In this case, it's probably safe to override the sortDescriptorWithKey:ascending: method with a category, which will give both iOS 3 and iOS 4 support, since my version will almost certainly do the same thing. 在这种情况下,使用类别覆盖sortDescriptorWithKey:ascending:方法可能是安全的,这将给予iOS 3和iOS 4支持,因为我的版本几乎肯定会做同样的事情。 I'd still prefer not to mess with system defined methods if possible, due to the (unlikely) possibility of breaking things in edge cases. 如果可能的话,我仍然不愿意混淆系统定义的方法,因为在边缘情况下(不太可能)破坏事物。

Joshua's answer will work well, but if you want to get really fancy, you can use the dynamic nature of Objective-C to modify the NSSortDescriptor class to your liking: Joshua的答案会很好用,但是如果你想变得非常花哨,你可以使用Objective-C的动态特性来根据自己的喜好修改NSSortDescriptor类:

#import <objc/runtime.h>

SEL theSelector = @selector(sortDescriptorWithKey:ascending:);

if ( ! [NSSortDescriptor instancesRespondToSelector:theSelector]) {
    class_addMethod([NSSortDescriptor class],
                    theSelector,
                    (IMP)mySortDescriptorWithKey,
                    "@@:@B");
}

Of course, that depends on a C function: 当然,这取决于C函数:

id mySortDescriptorWithKeyAscending(id self, SEL _cmd, NSString *key, BOOL ascending) {
    // Put your code here.
}

DISCLAIMER: I have not tried to compile any of this. 免责声明:我没有尝试编译任何此类内容。

DISCLAIMER II: This may be frowned upon by Apple in terms of App Store submission. 免责声明II: Apple在App Store提交方面可能不赞成这一点。

Not directly, no. 不直接,没有。

The way I'd recommend doing this would be to have a my_sortDescriptorWithKey: which can then check if the class responds to sortDescriptorWithKey: and uses that if it does, otherwise use your own implementation. 我建议这样做的方法是拥有一个my_sortDescriptorWithKey:然后可以检查该类是否响应sortDescriptorWithKey:如果是,则使用它,否则使用您自己的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM