導言:最近同事在開發(fā)項目過程中蔓罚,因開發(fā)需求氮兵,需要代碼中調用第三方pod庫某個類的對象的私有方法(.m中定義的方法
)。
通過多方調研追逮,發(fā)現可以通過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];