objective-cstaticivars

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?


Solution

  • 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 – i.e. to use an ivar. This approach is called "object oriented design".