objective-c - 如何防止 Objective-C 中的继承?

标签 objective-c objective-c-runtime

如何在 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/

相关文章:

objective-c - 在 NSView Controller 中获取按键按下事件

objective-c - 如何为自定义 NSWindow 制作动画

ios - 关于 objc_getClass 的困惑

objective-c - 用于跟踪 iOS 设备上的 Objective-C 调用的 GDB 脚本 - 问题

ios - NSUserDefaults standardUserDefaults setInteger for a long long int

ios - 由于内存不足错误无法打开 SQLite 数据库

objective-c - 无法从NSTask的stdout获得中间输出?

ios - 在 Objective-C 中将自定义类注入(inject)子类继承树

Objective-C 属性表达式地址

ios - objc_setAssociatedObject 和 objc_getAssociatedObject 有什么问题吗?