the general approach looks good to me but why the string compare? Going after the class's name doesn't seem clean
here's a variant that does it comparing the Class
objects:
#import <Foundation/Foundation.h>
@interface A : NSObject
@end
@implementation A
+ (id)allocWithZone:(NSZone *)zone {
Class cls = [A class];
Class childCls = [self class];
if (childCls!=cls) {
[NSException raise:@"Disallowed Inheritance." format:@"%@ tried to inherit %@.", NSStringFromClass(childCls), NSStringFromClass(cls)];
}
return [super allocWithZone:zone];
}
@end
@interface B : A
@end
@implementation B
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
A *a = [[A alloc] init];
NSLog(@"%@",a);
B *b = [[B alloc] init];
NSLog(@"%@",b);
}
}