在初始化方法中使用父属性的Objective-C [英] Objective-c using parent properties in init method

查看:61
本文介绍了在初始化方法中使用父属性的Objective-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到在init方法中使用属性被认为是不好的做法.但是我应该使用父类属性吗?

I read that using properties in init method is considered as bad practice. But should I use parent class properites ?

例如

-(id) init
{
    if (self = [super init])
    {
        self.parentProp = someVal; // (1)
        parentProp = someVal; // (2)
    }

    return self;
}

什么是首选(1或2),为什么?谢谢!

What is prefered (1 or 2) and why? Thanks!

推荐答案

在调用super的init方法并返回后,对象的超类部分已初始化并可以使用.这是正常现象,并希望您在此之后使用其属性访问器.例如.如果创建UIViewController的子类,则通常在init方法中设置(继承的)title属性或修改navigationItem.

After you've called super's init method, and it has returned, the superclass's part of your object is initialized and ready for use. It's normal and expected that you use its property accessors after that. For example. If you make a subclass of UIViewController, it's normal to then set your (inherited) title property, or modify your navigationItem, in your init method.

也就是说,您可以打破这种行为.如果您覆盖了超类的一种方法(包括其访问器方法之一),然后又在init方法中调用了该方法,则由您确定在完全初始化对象之前,被覆盖的方法将正常运行.

That said, you can break this behavior. If you've overridden one of your superclass's methods (including one of its accessors methods), and then you call that method in your init method, it's up to you to be sure your overridden method will behave properly before your object is fully initialized.

更巧妙地,也许您覆盖了一个超类方法,然后又调用了一个没有被覆盖的超类方法.好吧,如果调用的方法转过身来并调用了覆盖的方法怎么办?您还需要意识到这种可能性.

More subtly, maybe you're overridden a superclass method, and then you call a different superclass method that you haven't overridden. Well, what if the method you call turns around and calls the method you have overridden? You need to be aware of this possibility too.

所有这些,我重申,通过调用父类的init方法之一对其进行初始化后,使用超类的属性访问器对其进行自定义是完全正常的.

All that said, I reiterate that it's perfectly normal to use your superclass's property accessors to customize it after you have initialized it by calling one of its init methods.

这篇关于在初始化方法中使用父属性的Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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