Possible Duplicate:
Why doesn’t Objective-C support private methods?
Private Method Declaration Objective-C
What I would like to do is make the implementation of a particular method in Objective C private (to use a Java term). That is, a method that the class can call as needed without any worry that the method will be overridden by a subclass. Perhaps the term is "safe from being overridden."
As an example, an object has multiple init methods, and there's a private initialize method to do the common initializations:
- (void) initWithFile:(NSString *)file
{
if ((self = [super init]) != nil) {
self.file = file;
self.url = nil;
[self initialize]
}
return self;
}
- (void) initWithURL:(NSURL *)url
{
if ((self = [super init]) != nil) {
self.url = url;
self.file = nil;
[self initialize]
}
return self;
}
- (void) initialize
{
...
}
This works, and if initialize isn't declared in the .h file, it's "protected" from being called by other classes.
I get into problem with subclasses (assuming the following class is a subclass of the previous example):
- (void) initWithFile:(NSString *)file
{
if ((self = [super initWithFile:file]) != nil) {
[self initialize]; // my local initializations
}
return self;
}
- (void) initialize
{
... // my private stuff
}
The problem is that in this example, the base class's initialize method is now never called, and the subclass's initialize method is called twice, since the subclass's initialize method is overriding the base class method.
I know I could call [super initialize] in the subclass, and omit the call in the subclass init method, but that requires the subclass to know the internals of the base class. Since the subclass shouldn't need access to the source of the base class, and should only need the .h interface file, it has every reason to think that it can implement an initialize method without causing the unwanted side-effect of changing the behavior of the base class.
I'm asking this because I had an issue that was directly involved with properties not being set in an initialize function, only to find out it was being usurped by a subclass, and it took me some time to debug this. I'd like to prevent this from happening in the first place.