ios - 如何在 iOS 上调配类方法?

标签 ios iphone objective-c swizzling

Method swizzling 非常适合实例方法。现在,我需要调配一个类方法。知道怎么做吗?

试过这个但它不起作用:

void SwizzleClassMethod(Class c, SEL orig, SEL new) {

Method origMethod = class_getClassMethod(c, orig);
Method newMethod = class_getClassMethod(c, new);

if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
    class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
else
    method_exchangeImplementations(origMethod, newMethod);
}

最佳答案

事实证明,我并不遥远。这个实现对我有用:

void SwizzleClassMethod(Class c, SEL orig, SEL new) {

    Method origMethod = class_getClassMethod(c, orig);
    Method newMethod = class_getClassMethod(c, new);

    c = object_getClass((id)c);

    if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
        class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    else
        method_exchangeImplementations(origMethod, newMethod);
}

关于ios - 如何在 iOS 上调配类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3267506/

相关文章:

ios - UIView 发出匹配边框形状的环

iphone - 加载缩略图时内存泄漏

ios - 如何在 objective-c 中以编程方式更改字体样式

objective-c - 将 NSLocalizedRecoveryOptionsErrorKey 设置为 NSError UserInfo 不提供任何恢复选项

ios - 在uigridview中的行和列设置图像

iphone - 试图将 long long 从 String 保存到 NSNumber

ios - 在运行时替换 ios 应用程序的 url 方案?

iphone - 适用于 Iphone 应用程序的 OCR

iphone - tableView.contentInset 在 iOS 7 上损坏

ios - 如何使用 gmail Api iOS 显示完整的邮件详细信息