Limit method invocation to a specific area of ​​a class in Objective-C

The problem is that my "private" (_init) method is accidentally overridden by a subclass and then no longer called:

@implementation Super - (void)_init { } - (id)init { [self _init]; return self; } @end @implementation Sub - (void)_init { } - (id)init { self = [super init]; if (self) { [self _init]; } return self; } @end 

I realized that such problems can only be solved if I can limit the calls of private methods to the current class scope (for example, the effect of the scope resolution operator in C ++). But is this possible in Objective-C?

Remember that directing you to change the names of private methods is not anders. The whole point of this problem is an accident - I could subclass another class and accidentally stumble upon its private methods.

+4
source share
1 answer

One solution is to refuse to use [] to send a message using IMP instead:

 - (id)init { self = [super init]; if (! self) return nil; // get the implementation pointer of -[Super _init]... IMP superInit = class_getMethodImplementation([Super class], @selector(_init)); // ...and call it superInit(self, @selector(_init)); return self; } 

Or, if you do not want subclasses to see this method at all, make a file scope function instead:

 static void customInit(Super *self) { } - (id)init { self = [super init]; if (self) customInit(self); return self; } 

Keep in mind that if you are developing Apple platforms, then you should not use the underscore as a prefix to indicate that the method is private: Apple reserve is an agreement . Otherwise, you may inadvertently override Apple's private method.

+3
source

All Articles