Runtime-iOS开发中的利器

2018-11-06  本文已影响0人  jackli007

导言:最近同事在开发项目过程中,因开发需求,需要代码中调用第三方pod库某个类的对象的私有方法(.m中定义的方法)。
通过多方调研,发现可以通过Runtime实现此种需求。感谢stackoverflow([Steazy])的强大,参考网址(https://stackoverflow.com/questions/14635024/using-objc-msgsendsuper-to-invoke-a-class-method
I made a "normal" Objective-C method for this on a category of NSObject, which will work for both instance and Class objects to allow you to invoke a superclass's implementation of a message externally. Warning: This is only for fun, or unit tests, or swizzled methods, or maybe a really cool game.

代码实现:

@implementation NSObject (Convenience)

-(id)performSelector:(SEL)selector asClass:(Class)class
{
    struct objc_super mySuper = {
        .receiver = self,
        .super_class = class_isMetaClass(object_getClass(self)) //check if we are an instance or Class
                        ? object_getClass(class)                //if we are a Class, we need to send our metaclass (our Class's Class)
                        : class                                 //if we are an instance, we need to send our Class (which we already have)
    };

    id (*objc_superAllocTyped)(struct objc_super *, SEL) = (void *)&objc_msgSendSuper; //cast our pointer so the compiler can sort out the ABI
    return (*objc_superAllocTyped)(&mySuper, selector);
}

接下来:

[self performSelector:@selector(dealloc) asClass:[self superclass]];

等价于:

[super dealloc];
上一篇 下一篇

猜你喜欢

热点阅读