views:

38

answers:

1

Is it possible to share one parameter of a class among all the instances of this class, in objective-c?:

@interface Class1 : NSObject {
    NSString* shared; /** shared among instance (this is not, but defined somehow) **/
    NSString* non_shared; /** other parameters non shared **/
}

In the program then, each instance of Class1 has its own non_shared variables (as usual), but all access the same shared one (when one instance changes it all can see it).

One possibility is to hide the variable as a property and use a singleton in the setter/getter functions, but I don't know if there is a simple way.

Thanks, Edu

+2  A: 

Class variables (called static in many other OOP languages) are actually a bit of a pain in Objective-C. You have to declare a static global variable in the class' module (.m) file and reference that variable. You should add class-level getter/setters to encapsulate access to the static global variable. Your getter can alloc/init an object and put it in the variable if it is uninitialized before returning it.

If the static variable holds an instance (e.g. an NSString instance in your example), you need to make sure it doesn't get alloc/initialized more than once. Take a look at dispatch_once if you're on OS X 10.6 or greater to guarantee single initialization.

Barry Wark