如何防止 Objective-C 中的继承?
我需要阻止它,或者发出参考项目文档的编译器警告。
我想出了以下内容,我不确定它是否适用于所有场景。
主要的
#import <Foundation/Foundation.h>
#import "Child.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Child *c = [[Child alloc] init];
}
return TRUE;
}
家长班
。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
儿童班
。H
#import <Foundation/Foundation.h>
#import "Parent.h"
@interface Child : Parent
@end
.m
#import "Child.h"
@implementation Child
@end