English 中文(简体)
在目标c中,我应在哪里开始设定变量?
原标题:Where should I initialize variables in objective c?

在目标 c 中, 我是否应该覆盖初始化变量的初始化方法? 如果变量是属性, 我仍然可以用通常的方式访问这些变量, 来设定它们的初始值?

最佳回答

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

是,具体地说,指定初始化器。

您的子类还可以指定另一个构建阶段( 例如查看过Load ) 。 另外, 对象的内存在分配时为零, 所以您不需要将其明确设定为 0/ nil (除非您发现它更易读) 。

如果变量是属性, 我仍然可以用通常的方式访问它们, 以设定它们的初始值?

您应该避免使用对象实例方法/ 访问器, 避免直接在部分构造状态( 特别是初始化器和交易器) 中访问 ivars。 您想要避免的副作用有多种 - < a href=" https:// stackoverflow. com/ questions/5932677/ 初始化- a- property- dot- notation/ 5932733# 5932733" > 这里的例子 < /a > ;

问题回答

您可以在视图控制器的Load 方法下初始化变量。

类别界面中宣布的变量将自动初始化为默认值, 完整值为 0, 类别和指点为 N/ NULLL 。 如果您需要将变量初始化为其他值, 您则需要推翻您所属的保障切入点。 例如, 一个自定义类继承 NSBject / code > 。 例如, 您将简单覆盖 < code> > init 。 如果您在一个从 < code> > NIB < / code > 文件装入的查看控制器操作中工作, 那么您可以覆盖 initOncoder: 或 < a href="https:// developerer. applebraryrary/mac/ documentation/ CocoferenceKit/Propermes/ / NSNibrefar_ reference > 。 html / applepplex_ redustroy you a firal firal first it a sual devidustrate doal supdustration you.

我是否应该覆盖初始化变量的初始化方法?

实例变量:是的,尽管它们已默认为 0/nil/false 。

如果变量是属性, 我仍然可以用通常的方式访问它们, 以设定它们的初始值?

是的,你可以。苹果会建议反对它,因为一个子类可能推翻了设置的存取器来做一些意外的事情。实际上,这很少是一个问题。





相关问题
How to change out-of-focus text selection color in Xcode?

Okay, I ll bite. I ve got really pleasant code/window colors set up in Xcode. Ordinarily, my selection color is very visible. When I am doing a project search and iterating through the results, ...

Iphone NSTimer Issue

Hi I am new to objective c. I am trying to make an app for iphone. I have a button on my view, and the click on which the function playSound is called. This is working properly. It does plays the ...

Include a .txt file in a .h in C++?

I have a number of places where I need to re-use some template code. Many classes need these items In a .h could I do something like: #include <xxx.txt> and place all of this code in the ....

Iterating over string/strlen with umlauted characters

This is a follow-up to my previous question . I succeeded in implementing the algorithm for checking umlauted characters. The next problem comes from iterating over all characters in a string. I do ...

Xcode open two editor windows with same file

Is it possible to open the same file in two separate windows in Xcode. I can open a file in one window and the same file in the main Xcode editor window, but I wanted two separate fulltime editor ...

Forcing code signing refresh in Xcode

In our environment, we share resources across multiple projects and platforms. When building for iPhone, only a subset of those resources are needed. Since that subset is still considerable, we have ...