ios - 如何禁止继承init方法?

标签 ios iphone objective-c

我一直在努力寻找正确而明确的答案,因此我决定在这里提出问题。

我创建类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/

相关文章:

ios - 从表格 View 中删除不必要的行

iphone - GCD 获取队列名称/标签

iphone - MPMoviePlayerViewController 立即关闭

iphone - Objective-C : How to grab a number after a sub string from string

ios - obj-c 无法从搜索数组中找到索引/错误输出

ios - 是否可以在文本模式/非图形用户界面中编辑 IOS UI

ios - 加载具有与其 UICollectionView 不同的 alpha 值的 UICollectionViewCell

iphone - iOS中是否有办法观察按下主屏幕按钮?

iphone - 用于日出和日落的 Objective-C 库?

objective-c - UIDocument saveToURL : causing severe lag