【问题标题】:How to access superclass variable in subclass如何访问子类中的超类变量
【发布时间】:2012-04-09 23:38:03
【问题描述】:

我创建了两个 viewController 类,其中一个是另一个的超类。我在超类中有一个 nsstring 变量,我必须在子类中访问它,请指导我如何去做。这是我的代码

  @interface Superclass : UIViewController{
  NSString *message
  }
  @property(nonatomic,retain)NSString *message;
  -(id)init;
  @end


 @implementation Superclass
 @synthesize message;
 -(id)init{
{
[super init];
message=@"Hello";
return self;

 }


  @interface Subclass : Superclass{

  }

 @end


 @implementation Subclass

 - (void)viewDidLoad {

   UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Alert" message:self.message delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
[alert show];
[alert release];
  [super viewDidLoad];


 }

我的警报提示但没有消息。

【问题讨论】:

    标签: objective-c iphone superclass


    【解决方案1】:

    您可以使用super.variable 访问超类变量。

    【讨论】:

    • 使用了 super.message,但没有成功:(
    • 如果子类没有实现它自己的属性版本,'self.variable'就是你所需要的。
    • @jrturton。我知道。我没有意识到他没有子类版本。还是谢谢。
    【解决方案2】:

    你是如何初始化Subclass的?

    使用initWithNibName:bundle: 方法?

    在这种情况下,您的超类init 方法将不会被调用。所以重写超类中的initWithNibName:bundle: 方法并将值设置为那里的变量。

    【讨论】:

    • 之后在你想访问它的任何地方使用'message'和超类'对象......就像superclass.message......:)
    • 你还需要在你的超类中保留消息
    • 谢谢..它的工作...有什么方法可以让我直接访问变量而不覆盖 initWithNibName:bundle:?
    【解决方案3】:

    将变量声明为公共到超类中

    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Alert" message:message delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
    [alert show];
    

    【讨论】:

      【解决方案4】:

      只需使用

      self.message = @"something"

      ,超类的成员将被子类对象继承

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-08
        • 2017-08-22
        • 1970-01-01
        • 2022-01-05
        • 2018-08-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多