2013-09-01 95 views
3

如何防止Objective-C中的繼承?如何防止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 

蚩LD類

.H

#import <Foundation/Foundation.h> 
#import "Parent.h" 

@interface Child : Parent 

@end 

.M

#import "Child.h" 

@implementation Child 

@end 
+2

什麼是你的問題? – Codo

+0

爲什麼你需要防止繼承?這是某種形式的強迫症? – trojanfoe

+1

@trojanfoe不需要的繼承降低了可維護性。我已經更新了這個問題。 –

回答

3

的一般方法對我來說很好,但爲什麼字符串比較?類的名稱後會似乎並不乾淨

這裏的,做它比較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); 
    } 
} 
+0

看起來不錯,謝謝你的時間。 –

+0

您是否需要使用'NSStringFromClass()'來打印類名? – trojanfoe

+0

沒有[類描述]打印名稱 - 至少它現在工作 –