3

如何防止 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
4

1 回答 1

4

一般方法对我来说看起来不错,但为什么字符串比较?追随班级的名字似乎不干净

这是一个比较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);
    }
}
于 2013-09-01T08:45:56.213 回答