如何在init方法中访问超类的变量 [英] How to access super class's variables in init method

查看:58
本文介绍了如何在init方法中访问超类的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

超类Resource

@interface Resource : CoderObject

@property (strong, nonatomic) NSString *resourceID;
@property (assign, nonatomic) ResourceType resourceType;
@property (assign, nonatomic) DataType dataType;

@end

子类 ViewResource

@interface ViewResource : Resource

@property (strong, nonatomic) CustomView *view;
@property (strong, nonatomic) UIViewController *viewController;

@end

在子类ViewResourceinit方法中如何访问Resource的变量dataType?现在我想只使用 super.dataType = ...

In subclass ViewResource's init method how to access Resource's variable dataType? Now I'm trying to just use super.dataType = ...

还有其他方法吗?

推荐答案

你只需要使用 self.dataType.您的子类可以完全查看 .h 文件中定义的所有超类属性.使用 self.xxx 还使您能够在将来需要时覆盖访问器方法,而无需返回编辑所有使用代码.

You just need to use self.dataType. Your subclass has full visibility of all of the superclass properties defined in the .h file. Using self.xxx also gives you the ability to override the accessor methods if required in the future without coming back to edit all of your usage code.

看看你下面的链接,很公平.这些都是有效的点.访问器不应该有副作用,但你不能保证它们不会.如果该属性定义为超类,那么您有几个选择:

Looking at your link below, fair enough. Those are all valid points. Accessors shouldn't have side effects but you can't guarantee they won't. If the property is defined the superclass then you have a couple of options:

  1. 使用self.xxx设置属性,尽量保证没有副作用
  2. 在 super 上调用一个 init 方法,传递所需的参数,并在那里设置它们
  1. Use self.xxx to set the property and endeavour to ensure no side effects
  2. Call an init method on super, passing the required parameters, and set them there

这篇关于如何在init方法中访问超类的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆