Where to put local variables
cocoa, cocoa-touch, iphone, objective-c
Solution
If variables are needed only for a single run of a single method, then you declare them inside the method. You need to initialize them each time you enter the method. This is thread safe.
If variables are needed only in a single method, but you want them to keep their value between calls, declare them as static in the method. They are initialized to nil/0/false, or you can initialize them in the declaration. This is not thread safe.
If variables need to be accessed by any method or function in a single implementation file, and you only need one for the entire program, then declare them as static variable in the .m file. Declaring them as static stops them from being exported by the linker and clashing with other identically named global variables. They are initialized to nil/0/false by default, or you can initialize them in the declaration. This is not thread safe.
If variables need to be accessed by any method in an object, and each instance needs its own values, then you need an ivar, declare it in the interface between the { }. They are initialized to nil/0/false. You cannot initialize them to any other value at declartion time. You can initialize them in your object's init. This is thread safe if the object is accessed only from a single thread.
Problem
I have a view who's methods are called by the accelerometer updates in the view controller. I need more than one method to use and change certain variables, for example one method initializes the variable and another updates their value with each accel update. I know if they were only used on one method I could declare them inside that method and be fine. But since they are used in multiple methods I have been declaring them at the top of the implementation file, but not as static which I know believe is wrong. In some of Apple's sample code they always declare these in the interface file. What is the best way to do this and why? My current method: @implementation int foo; Alternative 1: @implementation static int foo; Alternative 2: @interface { int foo; Thanks,