我一直在努力寻找正确而明确的答案,因此我决定在这里提出问题。
我创建类A并在其中定义init方法:
@interface A : NSObject
- (id)initWithHealth:(int)hp;
@end
然后,我要创建从类A继承的类B,并在那里定义另一个init方法:
@interface B : A
- (id)initWithHealth:(int)hp andDamage:(int)dmg;
@end
总的来说,当我要实例化类B中的对象时,Xcode会建议我使用-(id)initWithHealth:(int)hp; 或-(id)initWithHealth:(int)hp andDamage:(int)dmg; 初始化方法。
如何禁止类B继承类A的init方法?我希望我的B类只有一个我定义的初始化方法。有没有办法做到这一点?
提前致谢。
最佳答案
您有几种选择:
选项1-使用旧的init
方法提供默认的“损坏”。在B
类中,您将添加:
- (id)initWithHealth:(int)hp {
return [self initWithHealth:hp andDamage:0]; // use an appropriate default
}
- (id)initWithHealth:(int)hp andDamage:(int)dmg {
self = [super initWithHealth:hp];
if (self) {
// do stuff with dmg
return self;
}
选项2-如果使用旧的
init
方法,则会导致运行时错误。在B
类中,您将添加:- (id)initWithHealth:(int)hp {
NSAssert(0, @"Dont use this");
return nil; // make compiler happy
}
我个人认为选项1是更好的选择。
关于ios - 如何禁止继承init方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20447904/