Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private methods using Categories in Objective-C: calling super from a subclass

I was reading how to implement private methods in Objective-C (Best way to define private methods for a class in Objective-C) and a question popped up in my mind:

How do you manage to implement protected methods, i.e. private methods that are visible to subclasses?

Suppose I have a MySuperClass with a Category containing all its private methods, and I want to implement a MySubclass overriding or calling super to one of the MySuperClass private methods. Is that possible (using the Categories approach towards implementing private methods)?

Take a look at some of this code, at the bottom there is the overriden method.

// ===========================
// = File: MySuperClass.h
// = Interface for MySuperClass
// ===========================

@interface MySuperClass : Object
...
@end

// ===========================
// = File: MySuperClass.m
// ===========================
#import "MySuperClass.h"

// =================================
// = Interface for Private methods
// =================================
@interface MySuperClass (Private)

-(void) privateInstanceMethod; 

@end

// =====================================
// = Implementation of Private methods
// =====================================
@implementation MySuperClass (Private)

-(void) privateInstanceMethod
{
  //Do something
}

@end

// ================================
// = Implementation for MySuperClass
// ================================
@implementation MySuperClass
... 
@end




// ===========================
// = File: MySubClass.h
// = Interface for MySubClass
// ===========================

@interface MySubClass : MySuperClass
...
@end


// ================================
// = Implementation for MySubClass
// ================================

#import MySubClass.h

@implementation MySubClass
//OVERRIDING a Super Private method.
-(void) privateInstanceMethod
{
  [super privateInstanceMethod]; //Compiler error, privateInstanceMethod not visible!
  //Do something else
}
@end

Hopefully somebody already figured this out.

Cheers!

like image 875
Lio Avatar asked Oct 17 '09 16:10

Lio


1 Answers

This GNUStep page describes one approach Section 4.5:

...The bright side of this is it allows you to simulate protected methods as well. For this, the writer of a subclass must be informed in some way about the protected methods, and they will need to put up with the compiler warnings. Alternatively, you could declare the Protected category in a separate interface file (e.g., "PointProtected.h"), and provide this interface file with the understanding that it should only be imported and used by a subclass's interface file.

like image 152
nall Avatar answered Oct 21 '22 00:10

nall