【问题标题】:How do I get a variable in the superclass for use in the subclass of that superclass?如何获取超类中的变量以用于该超类的子类?
【发布时间】:2015-07-10 20:34:30
【问题描述】:

基本上,我想显示和利用在超类中声明和设置的变量。

这是将变量设置为其字符的代码:

- (IBAction)additionSelect:(UIButton *)sender {

    _operation = '+';

    _operationChosenMessage.text = [NSString stringWithFormat:@"You chose %c", _operation];

}

- (IBAction)subtractionSelect:(UIButton *)sender {

    _operation = '-';

    _operationChosenMessage.text = [NSString stringWithFormat:@"You chose Subtraction"];


}

这是显示变量的使用:

if([self operation] == '+'){
        if (_firstNumber + _secondNumber == [_writeNumber.text intValue]) {
            _score++;
        }
    }else if ([self operation] == '-'){

        if (_firstNumber - _secondNumber == [_writeNumber.text intValue]) {
            _score++;
        }

    }
    _firstNumber = (arc4random() % 40) - 20;

    _secondNumber= (arc4random() % 40) - 20;



        _displayEquation.text = [NSString stringWithFormat:@"%i %c %i", _firstNumber,self.operation,_secondNumber];

_operation 是在超类(1st sn-p) 中声明和设置的 char 变量,我想在子类中使用它。

【问题讨论】:

  • [自操作]应该返回什么?我认为这是一个 void 方法,它什么也不返回
  • 一个字符,可以是 + 或 -,具体取决于您之前在情节提要中选择的按钮。
  • 可以发一下【自操作】的代码吗?
  • 重要的是如何定义操作 ivar/property。如果基类定义了操作属性并且[auto]synthesizes _operation ivar,假设它没有重新声明操作,在子类中访问它应该没有问题。请发布您的超类和子类的接口。

标签: objective-c superclass


【解决方案1】:

为此,您需要在包含第一个代码 sn-p(超类)的类的接口中声明一个公共属性:

@interface SomeClass : NSObject
@property (nonatomic) NSString *operation;
@end

当您以这种方式声明属性时,会在后台创建 _operation iVar,这就是您的代码(如 _operation = '+')将继续按原样工作的原因。在您的子类中,您可以随时使用self.operation 访问此属性。如果您不希望您的子类编辑该属性,您可以将其声明为(nonatomic, readonly)。不要在您的子类中添加同名的属性,因为这会覆盖您的超类属性。

【讨论】:

  • 非常感谢。我真的很感激。
【解决方案2】:

您需要为此在子类可以看到的地方声明一个“getter”。你可以把它放在超类的头文件中,或者你可以制作一个只有某些类导入的私有头文件。

【讨论】:

  • 我使用了@property 并尝试了您在上面看到的方法。那样可以么?因为它仍然不起作用
  • objc 不是还有受保护的 ivars 吗?
  • @RahulShah 你在子类或超类中声明了属性吗?如果在子类中,则在那里合成,从而隐藏原始 ivar。
  • 我是在超类中做的,因为变量需要设置为等于超类中的一个字符
猜你喜欢
  • 1970-01-01
  • 2016-05-27
  • 2012-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多