Accessing a method in a super class when it's not exposed

时间秒杀一切 提交于 2019-11-29 03:11:43

The way I've dealt with this is to re-declare your super class' interface in your subclass implementation file with the method you want to call from the subclass

@interface MySuperclass()
- (void)superMethodIWantToCall;
@end

@implementation MySubclass


- (void)whateverFunction  {
    //now call super method here
    [super superMethodIWantToCall];
}

@end

I'm not sure if this is the best way to do things but it is simple and works for me!

This doesn't work because you're only sending performSelector:, not the selector you pass to that, to the superclass. performSelector: still looks up the method in the current class's method list. Thus, you end up with the same subclass implementation.

The simplest way to do this may be to just write in your own call to objc_msgSendSuper():

// Top level (this struct isn't exposed in the runtime header for some reason)
struct objc_super
{
    id __unsafe_unretained reciever;
    Class __unsafe_unretained superklass;
};

// In the subclass's method
struct objc_super sup = {self, [self superclass]};
objc_msgSendSuper(&sup, _cmd, other, args, go, here);

This can cause problems in the general case, as Rob Napier has pointed out below. I suggested this based on the assumption that the method has no return value.

Ismael

One way to go is to create a category of your class in a separate file with the method you are trying to expose

@interface MyClass (ProtectedMethods)

- (void)myMethod;

@end

and on the .m

@implementation MyClass (ProtectedMethods)

- (void)myMethod {

}

@end

Then, import this category from your .m files, and you're good to go. It's not the prettiest thing, but it'll do the trick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!