简体   繁体   English

Objective-C - 静态字段或基本类型的ivar

[英]Objective-C - Static field or an ivar for a primitive type

I've recently got stuck in the middle of choosing between an ivar and static field. 我最近陷入了在ivar和静态场之间进行选择的困境。 For instance: I need to toggle traffic lights between red and green. 例如:我需要在红色和绿色之间切换红绿灯。 So I put a flag called isRed.I've so far used a static bool for this purpose and it has served quite well. 所以我放了一个名为isRed的标志。到目前为止,我已经使用了一个静态bool用于此目的,它已经很好地服务了。 Now I think I can also use instance variables for this but I don't know the difference between them.What is the real difference between these two ways? 现在我想我也可以使用实例变量,但我不知道它们之间的区别。这两种方式之间真正的区别是什么?

When you know that there is (and ever will be) exactly one traffic light in your application, you can use a variable with static storage duration (what you call a static field). 当您知道应用程序中存在(并且将来)只有一个交通信号灯时,您可以使用具有静态存储持续时间的变量(您称之为静态字段)。

In almost all cases it is preferable to put state into the classes that control the state – ie to use an ivar. 在几乎所有情况下,最好将状态放入控制状态的类中 - 即使用ivar。 This approach is called "object oriented design". 这种方法称为“面向对象设计”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM