如何调整私人班级的方法 [英] How to swizzle a method of a private class

查看:167
本文介绍了如何调整私人班级的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个私有类(在.m中声明和定义)作为对不同类的实现的补充,恰好在内部使用该私有类。

I have a private class (both declared & defined within .m) as an addition to an implementation of a different class, that happens to use that private class internally.

我想调动那个私人班级的方法之一。

I'd like to swizzle one of the methods of that private class.

我定义了一个类别并按常规进行:

I defined a category and did the usual:

+(void)load 
{
    Method original, swizzled;

    original = class_getInstanceMethod(objc_getClass("SomePrivateClass"), @selector(somePrivateMethod:));
    swizzled = class_getInstanceMethod(self, @selector(swizzled_somePrivateMethod:));
    method_exchangeImplementations(original, swizzled); 
}

问题是我的实现显然对此私有类一无所知而self指的是我正在添加类别的类,无论哪个类都可以。因此,我无法调用原始实现,并且通常使用私有类。

The issue is that my implementation obviously doesn't know anything about this private class and self refers to the class I am adding the category to, whichever class that might be. So I have no way of calling the original implementation and in general working with the private class.

解决此问题的正确方法是什么?

What is the proper approach to tackle this?

推荐答案

管理让它工作,实际上非常简单。

Managed to get this to work, it's pretty simple actually.

所以我做的方式它:


  • 制作了一个NSObject类别: @interface NSObject(PrivateSwizzleCategory)

  • swizzled:

  • made a NSObject category: @interface NSObject(PrivateSwizzleCategory)
  • swizzled:

+(void)load
{
    Method original, swizzled;

    original = class_getInstanceMethod(objc_getClass("SomePrivateClass"), @selector(somePrivateMethod:));
    swizzled = class_getInstanceMethod(self, @selector(swizzled_somePrivateMethod:));   
    method_exchangeImplementations(original, swizzled);
}


  • 要调用原始实现,我必须将self转换为NSObject :

  • To call the original implementation, I had to cast self to NSObject:

    id ret = [(NSObject *)self swizzled_somePrivateMethod:someParam];
    


  • 要访问私有类的私有属性,我在self上使用了valueForKey:

  • To access private properties of the private class, I used valueForKey on self:

    id privateProperty = [self valueForKey:@"__privateProperty"];
    


  • 一切正常!

    这篇关于如何调整私人班级的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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