How to swizzle a method of a private class

前端 未结 1 482
不思量自难忘°
不思量自难忘° 2021-01-02 08:54

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.

相关标签:
1条回答
  • 2021-01-02 09:34

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

    So the way I did it:

    • 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);
      }
      
    • To call the original implementation, I had to cast self to NSObject:

      id ret = [(NSObject *)self swizzled_somePrivateMethod:someParam];
      
    • To access private properties of the private class, I used valueForKey on self:

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

    Everything works!

    0 讨论(0)
提交回复
热议问题