views:

93

answers:

2

When we should use global variable and when class variable and why?

I hope your experiences and ideas to share with us who are novice in this platform.

Example:

Let, i need to trace timestamp and position of touch events (eg. touch start, end) on a layer. I can trace it using global variable or class variable of the class which implements touch event. What should I do?

Regards,

-Sadat

+1  A: 

It's kind of a flip answer, but don't use global variables at all - stick with class methods and expected encapsulation. Anything else and you'll be fighting the cocoa libraries from dusk to dawn. If you follow their patterns, which include class methods, encapsulation, delegation, etc - you'll be making huge headway with relatively little effort.

The only place where I might think to call something a "global variable" in my efforts are project-wide constants - so not variables at all, but sometimes there's a good need for a constant across your project (TableViewCell identifiers comes to mind)

heckj
+2  A: 

This isn't a problem specific to Objective C or the iPad family of devices.

Variables should have the minimum "visibility" and "duration" that they need, and no more.

You would have to come up with some very convincing reasons for trying to get a global variable through our code review processes. They're almost always able to be replaced with something a little more appropriate.


In response to your comment:

I don't know how global/class variable affects on memory.

There's a nice snippet over here which details how to do class level variables. These are normal C file-scoped variables so they're not visible outside the file but you only get one for the class, not one for every object that you instantiate.

In that sense, they have the advantages of a global (minimal storage and the value is still accessible for reading) without the disadvantages (polluting the global name-space and making it possible for code outside of the class to change it).

And, if it doesn't need to be read outside of the file, just don't provide the initCount method.

paxdiablo
Snark aside, this answer is dead on. Limiting the scope of variables to exactly the scope of use leads to a better, more modular, design. It'll also help greatly if, deities forbid, you have to add concurrency later.
bbum
@paxdiablo: iPad/iPhone or objective-c comes, because of MEMORY issue. I don't know how global/class variable affects on memory.
Sadat