如何在 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
最佳答案
一般方法对我来说看起来不错,但为什么要比较字符串?追求类(class)的名字似乎不太干净
这是比较 Class
对象的变体:
#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);
}
}
关于objective-c - 如何防止 Objective-C 中的继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18556407/