In Java, a factory constructor can be defined in an abstract superclass like:
public static Parent createChildFromType(int type) {
switch (type) {
case 0:
return new Child1();
case 1:
return new Child2();
default:
throw new Exception();
}
}
But, in Objective-C, I'm getting a 'No known class method for selector "alloc"' for case 1
:
#import "Child1.h"
#import "Child2.h"
@implementation Parent
+(id)createChildFromType:(int)type {
switch (type) {
case 0:
return [[Child1 alloc]init];
case 1:
return [[Child2 alloc]init];
default:
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"Invalid subclass type."
userInfo:nil];
}
}
-(void)someAbstractMethod {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:[NSString stringWithFormat:@"You must override %@ in a subclass.",
NSStringFromSelector(_cmd)]
userInfo:nil];
}
@end
Both Child1.h
and Child2.h
have #import "Parent.h"
because I'd like to make a call to someAbstractMethod
, without knowing beforehand, which subclass I'm calling it on:
-(void)someVoodooMethod:(int) type {
Parent *child = [Parent createChildFromType: type];
[child someAbstractMethod];
}
I have a hunch that it's because of the redundant #import "Parent.h"
in the @implementation Parent
, but I haven't thought of a way around it. Any suggestions?
EDIT:
I suppose the code for Child1.h
should be included:
#import "Parent.h"
@interface Child1 : Parent
@end
And Child2.h
#import "Parent.h"
@interface Child2 : Parent
@end