Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

North Bronson

macrumors 6502
Original poster
Oct 31, 2007
395
1
San José
I had a question about declaring static variables for my Objective-C app.

Right now, I have two classes: FirstModel and SecondModel.

The implementation for FirstModel looks like:

Code:
#import "FirstModel.h"

static NSString *staticString = @"This is the First Model.";

@implementation FirstModel

//  Here is the code.

@end

The implementation for SecondModel looks like:

Code:
#import "SecondModel.h"

static NSString *staticString = @"This is the Second Model.";

@implementation SecondModel

//  Here is the code.

@end

The goal is that whichever class I'm in, a method of that class can access staticString for the appropriate message.

The C texts that I'm looking at don't really explain this that well to me. Is this an appropriate use of the static declaration? Is static unnecessary because they are contained in separate files?

I've declared static variables in methods and functions before, but declaring static variables outside of methods or functions is a little new to me.
 
Personally I use static variables to keep hold of data that I don't want to change, but access it from all methods in the implementation.

Right now I am using quite a few static variables in OpenGL so that I do not accidentally change data that could crash the app.

So I think what you are trying to do with them is viable, although I am sure that someone will contradict me. And no static is not unnecessary as I say if you do not want the data changed by accident, but also to be available to all methods then a global static variable is the way to go, although I may be contradicted.

Hope this helps somewhat.

Stephen
 
In C (and thus I assume Objective-C) a variable declared with the static modifier when the variable is in a global position basically means that it has file scope. That is to say the variable is only accessable from that particular source code file and you can declare a variable with the same name in a different file so long as it also has static scope.

Edit: I should also point out that declaring variables as static means that the memory that is allocated to them is allocated only once and is not freed at all until the program terminates. This is fine for int's char's for instance but if you declare a large array as being static it may have consequences that you did not initially forsee.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.