Note: What follows is another post in an on-going series for developers who are interested in learning to write applications for the iPhone. The entire series can be found here: iPhone Developer .
One common complaint for many new to Objective-C is that the language lacks support for private methods within a class. There are compiler directives for instance variables: @private, @protected (the default) and @public. However, if you want to hide methods, there is no specific directives to help. The example here builds on the previous post on working with categories.
Ultimately, there is no means to make a method private in Objective-C. However, one can hide methods in a class as I show here. It’s important to understand, this still does not make the methods private, it just makes them “harder to find” if you will.
To implement hidden methods (instance and/or class) you can use categories . Let’s begin with a file called SomeClass.h, the interface definition for SomeClass.
// = File: SomeClass.h
// = Interface for SomeClass
@interface SomeClass : Object
Nothing too interesting here, simply an interface declaration for a class with two methods: msg and classMsg . By definition (of the language) both methods are publicly accessible. Now, let’s look at the corresponding implementation file shown below. Begin at the bottom where I write the implementation for the two methods above. Again, nothing new, so far. Now, if you start at the top of this file, notice how I’ve added an interface for SomeClass (similar to the interface definition above), however, I added (hidden) to the definition, which now makes the interface definition a category. Just below the definition, I write the code for the two methods in the category.
// = File: SomeClass.m
// = Interface for hidden methods
@interface SomeClass (hidden)
// = Implementation of hidden methods
@implementation SomeClass (hidden)
printf( "Hidden class method.\n" );
printf( "Hidden instance method\n" );
// = Implementation for SomeClass
To see what this does for us, look at the code below, followed by the screenshot:
// = File: Main.m
int main (int argc, char *argv)
SomeClass *ptr = [[SomeClass alloc] init];
// Display message (including messages from hidden methods)
// Call a class method
// Compile warning (can't access hidden instance method)
// [ptr hiddenInstanceMethod];
// Compile warning (can't access hidden class method)
// [SomeClass hiddenClassMethod];
Notice how I can access the hidden instance and class methods from within the class. However, if I remove the comments from lines 17 and 20, to attempt access to the hidden methods, the compiler generates the following warnings:
I’m not sure if this is the only means to hide methods. If you know of another way (and have a code example), please post a comment.
The output of the application is shown here:
Download the code and give this a try within Xcode.