我应该在哪里初始化目标 c 中的变量? [英] Where should I initialize variables in objective c?

查看:58
本文介绍了我应该在哪里初始化目标 c 中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在目标 c 中,我应该覆盖 init 方法来初始化我的变量吗?如果变量是属性,我还可以通过通常的方式访问它们来设置它们的初始值吗?

In objective c, should I overwrite the init method to initialize my variables? If the variables are properties can I still access them the usual way to set their initial value?

推荐答案

在目标 c 中,我应该覆盖 init 方法来初始化我的变量吗?

In objective c, should I overwrite the init method to initialize my variables?

是的.具体来说,就是指定的初始化器.

Yes. Specifically, the designated initializer(s).

您的子类还可以指定另一个构建阶段(例如 viewDidLoad).此外,对象的内存在分配时会被清零,因此您无需将它们显式设置为 0/nil(除非您觉得它更具可读性).

Your subclass may also specify another construction stage (e.g. viewDidLoad). Also, the object's memory is zeroed when it is allocated, so you do not need to set them explicitly to 0/nil (unless you find it more readable).

如果变量是属性,我还可以通过通常的方式访问它们来设置它们的初始值吗?

If the variables are properties can I still access them the usual way to set their initial value?

你应该避免使用对象的实例方法/访问器,并在部分构造的状态(特别是初始化程序和dealloc)中直接访问ivars.您需要避免许多副作用 - 此处示例;

You should avoid using the object's instance methods/accessors, and access ivars directly in partially constructed states (notably the initializer and dealloc). There are a number of side effects you will want to avoid - Example Here;

这篇关于我应该在哪里初始化目标 c 中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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