【发布时间】:2011-06-11 10:43:14
【问题描述】:
不需要添加特定类初始化代码的子类是否必须实现超类的指定初始化器?
Apple 的 NSObject 的 init 方法的文档提供了一些讨论:
“每个班级都必须保证 init 方法要么完全返回 类的功能实例或 引发异常。子类应该 覆盖init方法添加 类特定的初始化代码。”
"如果子类进行任何初始化 它自己的,它必须定义自己的 指定的初始化器。这种方法 应该首先发送一条消息到 super 调用指定的 其超类的初始化器。”
但是,当子类不需要额外的初始化代码时,没有指定任何内容。
下面的代码试图澄清我的问题。 ClassA 具有名为 initWithX:Y: 的指定初始化程序。 ClassB 不需要额外的初始化,一切都由 ClassA 提供。
解释代码:
@interface ClassA : NSObject {
NSInteger x;
NSInteger y;
}
- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY;
@end
@implementation ClassA
- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
if(self = [super init]) {
x = initX;
y = initY;
}
return self;
}
@end
@interface ClassB : ClassA {
//no extra variables
}
//some extra static methods add to provide some differences
// between ClassA and ClassB in sample code
+ (NSInteger)extraMethodOne;
+ (NSInteger)extraMethodTwoWithInteger:(NSInteger)anInteger;
@end
@implementation ClassB
/////////////??QUESTION HERE??///////////////////
//Is the implementation below needed?
//If I call [[ClassB alloc] initWithX:1 Y:2], won't it run the code in ClassA
// with the self set to whatever [ClassB alloc] is?
/////////////////////////////////////////////////
- (id)initWithX:(NSInteger)initX Y:(NSInteger)initY {
if(self = [super initWithX:initX Y:initY]) {
/* Don't need class-specific initialization code */
}
}
//some extra static methods add to provide some differences
// between ClassA and ClassB in sample code
+ (int)extraMethodOne {return 1;}
+ (int)extraMethodTwoWithInteger:(NSInteger)anInteger {return 2 + anInteger;}
@end
【问题讨论】:
标签: objective-c