Can Objective-C subclass without calling init
I'm using a third party library that doesn't not expose its init method
and does some specialized I-don't-know-what from class-level message. Does
that prohibit me from subclassing?
I made a test case (ARC enabled)
A.h
@interface A : NSObject
@property (nonatomic, strong) NSString * bar;
-(id) initWithAbar:(NSString *) bar;
+(id) aWithBar:(NSString *) bar;
@end
A.m
#import "A.h"
@implementation A
-(id) initWithAbar:(NSString *) bar
{
self = [super init];
if (self) {
self.bar = bar;
}
return self;
}
+(id) aWithBar:(NSString *) bar
{
return [[A alloc] initWithAbar:bar];
}
@end
B.h
#import <Foundation/Foundation.h>
#import "A.h"
@interface B : A
@property (nonatomic, strong) NSString *foo;
-(id) initWithFoo:(NSString *)foo bar:(NSString *)bar;
@end
B.m
#import "B.h"
@implementation B
-(id) initWithFoo:(NSString *)foo bar:(NSString *)bar
{
self = (B*)[A aWithBar:bar]; // Still actually A, knew that by
printing [self class];
if (self) {
self.foo = foo; // Error: unrecognized selector here
}
return self;
}
@end
Suppose I cannot just call A's initWithAbar:, any choice I have in
subclassing A? What's so special about init anyway if A's aWithBar is
calling A's init?
No comments:
Post a Comment