How to preventing inheritance in Objective-C?
I came up with the following, which I am not sure if works in all scenarios.
main
#import <Foundation/Foundation.h>
#import "Child.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Child *c = [[Child alloc] init];
}
return TRUE;
}
Parent Class
.h
#import <Foundation/Foundation.h>
@interface Parent : NSObject
@end
.m
#import "Parent.h"
@implementation Parent
+ (id)allocWithZone:(NSZone *)zone {
NSString *callingClass = NSStringFromClass([self class]);
if ([callingClass compare:@"Parent"] != NSOrderedSame) {
[NSException raise:@"Disallowed Inheritance." format:@"%@ tried to
inherit Parent.", callingClass];
}
return [super allocWithZone:zone];
}
@end
Child Class
.h
#import <Foundation/Foundation.h>
#import "Parent.h"
@interface Child : Parent
@end
.m
#import "Child.h"
@implementation Child
@end
No comments:
Post a Comment