【问题标题】:How to access super class's variables in init method如何在init方法中访问超类的变量
【发布时间】:2013-05-18 09:37:50
【问题描述】:

超级班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 = ...

还有其他方法吗?

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

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

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

    1. 使用self.xxx 设置属性并努力确保没有副作用
    2. 在 super 上调用 init 方法,传递所需的参数,并在那里设置它们

    【讨论】:

    • 但是我听说你不应该在init方法中调用self.method
    • 给出了什么理由?最好使用访问器方法来设置值。唯一不应该使用访问器的时候是当您在访问器内部时。
    • @Wain 实际上有一个关于它的大讨论。我更喜欢总是在 init/dealloc 中使用访问器,但如果你的设置器有自定义实现或者它们被覆盖,有时你需要重新排序语句。请注意,Apple 在 UIKit 中也是如此。
    • 我应该调用超类的init方法。
    【解决方案2】:

    就像 Wain 在他的回答中所说,您可以直接访问您的超级班级成员(如果他们不是私人的)。

    而且在init方法中调用self.property是没有问题的,只要你的init看起来像这样

    -(id)initAndTheNameYoWantAndMaybeSomeParameters:(NSString *)paramExample {
        self = [super initNameOfAnInitMethodFromSuperClass];
        //check if the init was with success
        if(self != nil) {
           self.myStringProp = paramExample;
           //or
           self.propertyFromSuper = paramExample;
        }
    }
    

    是的,你也可以在 initMethods 中做一些愚蠢的事情(我之前做过 :))),比如从它内部调用相同的 initMethod,它会生成一个递归调用,导致我的应用程序崩溃。 (很容易发现这个问题)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-28
      • 2023-02-15
      • 2017-08-22
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      相关资源
      最近更新 更多