In ObjC, how do I hide implementation a superclass

2019-09-12 07:18发布

问题:

In ObjC, how do I hide implementation a superclass's methods in a subclass?

I'm not sure if @private would do the trick, as it appears to only apply to ivars.

回答1:

There are no actually "private" methods in Obj-C; since any message can be sent to any object at runtime, there's no way to prevent someone from sending the message you care about.

That said, you can intercept that message in the subclass and not handle it. The simplest way to make a superclass's method inaccessible is to override it in the subclass and do nothing:

- (void)someMethodIDontWantToSupport
{
}


回答2:

You're right, the @private directive is for instance variables, not methods. To hide a method's implementation, simply omit its declaration from the header file. To suppress warnings, you can use use a category or class extension to declare the method in the .m file.

There's no built-in language feature to prevent a subclass from seeing the method, though. Why would you want to do that?