What is the reason for using 'static'? page 40


I do not understand why we use the keyword ‘static’ in front of randomAdjectiveList and randomNounList.

static NSString *randomAdjectiveList[3] ...
static NSString *randomNounList[3] ...

The program runs fine without using it.


Static can be interpreted as “only once.” Therefore, two C-arrays with three elements whose types are pointers to NSString (NSString *) are created when the program is loaded into memory. Each time the randomPossession method is executed, the very same randomAdjectiveList and randomNounList is used.

This is different than a typical local variable in a method. A local variable in a method,

- (void)foo
      NSString *randomAdjectiveList[3] = { ... };

is created on the stack every time the method is ran.

The literal NSString instances that make up the contents of these arrays are, because they are string literals, created when the program is loaded into memory as well. Therefore, none of these objects or variables are created each time the method runs, only once and you reuse them.


This makes sense ;-I



What’s the deal with static variables with respect to memory management?

I assume that the (new) syntax in this particular example (which looks like it’s making an array of NSStrings) calls alloc for each one behind the scenes the first time this code is run (the static ensuring it happens only once).

But they are never released (obviously, because static says they are needed again later). Do they just hang around for the lifetime of the application and get removed from memory when the application quits?


Remember that variables do not need to be memory managed. If they are a local variable, the memory they consume (4 bytes for a pointer, int, float, 8 for a double or long - either way, tiny amount) is freed when the method ends. If they are an instance variable, they are freed when the object is destroyed.

A static variable exists the entire time the application is running. The object it points doesn’t necessarily exist the entire time, but in this case, the object pointed to by these variables is a string literal and as such it exists the entire time the application is running.

Therefore, there are two things reserved in memory: the variables and the objects that they point to. It’s totally okay to have objects exist the entire time an application is running, many objects already do like UIApplication, its delegate, most view controllers, and a slew of other objects you don’t see. The memory for these objects is returned to the OS along with the rest of the memory an application was consuming when it is terminated.


Fair enough. It’s as I thought, but not a problem. Coolio.