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