Protected methods in objective-c

Posted by Nucc

In objective-c there is no language supported solution for private and protected class methods as in C++ or Java. The reason is Objective-c is only a layer on the language C which is (as it is known) not an object oriented langauge. The @protected and @private tags are only directives for the compiler to throw an error when other objects call methods in their scopes.

This compiler directives unfortunetly don’t work for methods, only for instance variables.

There are two workarounds to implement protected and private methods.

1. Let the private methods be part of the implementation file only. For instance:

  1.  
  2. Car.h:
  3.  
  4. @interface Car {
  5.     int   tires;
  6. }
  7.  
  8. -(id) init;
  9.  
  10. @end
  11.  
  12. Car.m:
  13.  
  14. @implementation Car
  15.  
  16. -(id) init
  17. {
  18.     [super init];
  19.     [self setupDefaultValues];
  20.     return self;
  21. }
  22.  
  23. // private function
  24. -(void) setupDefaultValues
  25. {
  26.     ; // Custom code
  27. }
  28.  
  29. @end

Using this approach your methods can be only private, which may occures problems in the future, when you try to overload a derived method, and you can not change its visibility to protected.

The compiler will throw a warning message for [self setupDefaultValues], because the compiler will be looking for this method in the @interface definition.

2. The second solution uses category pattern, which splits the header file into two parts. The main part contains the public, and the other includes the private part of your class.

In this example the Car.h is the same as in the first example, so I’ll just write the additional lines.

Car.h
----------------

@interface Car (PrivateMethods)

- (void) setupDefaultValues

@end

Car.m
----------------
@implementation Car (PrivateMethods)

- (void) setupDefaultValues
{
    ; // Custom code
}

@end

I haven’t found nice solution for protected methods yet. There is a convention to begin  protected methods with _ mark, but I like when the compiler warns me to somebody tries to call a protected method, and I’m not forced to dig up the code for checking prefixes.


Leave a Reply