Thursday 2 February 2012

Private Methods in Objective-C

Most mainstream OO languages (C++, Java) support the notion of private, protected, and public class members. I've debated for years whether these protection attributes are really worthwhile, but it seems the designers of Objective-C felt protection for methods was not necessary. While you can add the various protection attributes to class and instance fields, you cannot do the same for methods.
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

 

Copyright @ 2013 PakTechClub.