简体   繁体   中英

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. 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. 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. This approach is called "object oriented design".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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