I researched this question by playing around associative links (thanks to Ole ), with static variable methods, swizzling methods, and finally come up with this simple solution (no runtime). I just use the "categorized" class only to return a pointer to a derived class, which, of course, may contain additional ivars. As a result, I get one unexpected advantage: I can call methods of the super class, which is impossible when expanding into categories.
Class extension example ( verified ):
ClassA + ClassB.h
@protocol _ClassB_Protocol @optional // to avoid warnings - (IBAction) onClick:(id)sender; @property (nonatomic, retain) IBOutlet UIButton *aButton; @end @interface ClassA (_ClassA_Category) <_ClassB_Protocol> @end @interface ClassB: ClassA <_ClassB_Protocol> { UIButton *aButton; // _ivar_ to add } @end
ClassA + ClassB.m
@implementation ClassA (_ClassA_Category) // this will be called first on [ClassA alloc] or [ClassA allocWithZone:(NSZone *)zone] +(id) alloc { if ([self isEqual: [ClassA class]]) { return [ClassB alloc]; } else { return [super alloc]; } } @end @implementation ClassB: ClassA @synthesize aButton; -(void) dealloc { [aButton release]; [super dealloc];
Now we have the same time:
ClassB "extends" ClassA (category mode);ClassB inherits ClassA ( ClassB can call ClassA methods);ClassB can be obtained through the ClassA name (category method)
Martin Babacaev Feb 04 '11 at 15:09 2011-02-04 15:09
source share