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