There are several tricks you can employ, but I will present here the most straightforward and simplest approach. This trick uses the concept of class extensions, a bizarre facility that allows you to extend another class with replacement or additional methods. This technique is also sanctioned by the Apple Objective-C 2.0 Programming Language document (
The Objective-C 2.0 Programming Language). To add a private method to your class, you extend your own class within your implementation (.m) file. This way, clients of your interface (.h) file do not see or know about your methods. For example:
// .h file to declare our class
@interface MyClass
// this is a public method
- (void) sayHi;
@end
You'll notice in the header file, which is imported by users of your MyClass, has no mention of a private method. It is the implementation file where we put it:
// .m file to define our class
// but first let's extend our class with a private method
@interface MyClass ()
// this is a private method
- (void) tellSecret;
@end
// now we implement everything
@implementation MyClass
// the public method
- (void) sayHi
{
NSLog(@"Hello everyone!");
}
// the private method
- (void) tellSecret
{
NSLog(@"Psst, ...");
}
@end
0 comments:
Post a Comment