There is no such thing as a private method in Objective-C. Developers, however, use class extensions to declare the methods they don’t want to expose publicly, effectively making them ‘private’.
Let’s say you are subclassing a library class and to make it work for your application, you need to reimplement one of its private methods without replacing it. In other words, you still want be able to call super, but you also want to add your own code. Something like this:
1 2 3 4 5 6
Of course, because the method that you want to reimplement is not publicly documented, the compiler won’t let you do it. And you’ll receive a “No visible @interface declares the selector” error.
You might be thinking why not just move the private method declaration to the header (.h) file (making it a public method effectively.) But what if you wanted to keep the original library intact? What if it was a framework, or a library that you added using CocoaPods and you didn’t want to mess with?
Here’s a simple but hacky way to do it:
All you need to do is to declare a category and declare the private method there. You don’t even need to implement it. (unless of course, you want to override the original implementation, which is a different story)
1 2 3 4 5
Now, as far as the complier is concerned coolClassPrivateMethod is public, and is available to your subclass. Hence, you won’t get an error when you call
Bonus tip: Make sure you don’t get tempted to hack the private Cocoa methods, or Apple will reject your app!