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

Nic*_*rge 2 objective-c ios objective-c-category

在过去的项目(iOS 4.0之前),我写了以下类别方法NSSortDescriptor:

+ (id)sortDescriptorWithKey:(NSString *)key ascending:(BOOL)ascending;
Run Code Online (Sandbox Code Playgroud)

当Apple发布iOS SDK 4.0时,它包含了完全相同的方法(可能完全相同).是否可以编写一个仅在运行特定操作系统版本时才添加到运行时的类别,或者如果还没有使用相同签名声明的方法,则可能更多?

在这种情况下,sortDescriptorWithKey:ascending:使用类别覆盖方法可能是安全的,这将提供iOS 3和iOS 4支持,因为我的版本几乎肯定会做同样的事情.如果可能的话,我仍然不愿意混淆系统定义的方法,因为在边缘情况下(不太可能)破坏事物.

Jef*_*ley 5

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");
}
Run Code Online (Sandbox Code Playgroud)

当然,这取决于C函数:

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

免责声明:我没有尝试编译任何此类内容.

免责声明II: Apple在App Store提交方面可能不赞成这一点.