tags:

views:

20

answers:

1

I want to keep the value of a variable in my multiple class instances... Here is what I am doing: 1. Declaring a class level variable. 2. Setting it in inside one of my function during first initialization 3. Trying to fetch this during next object creation.

Here, I am not able to retain the value. Any clue?

I have this variable defined in my .h file:

@property (nonatomic, retain) NSString *mainServiceType; 

and then I am setting it in my method in .m file

self.mainServiceType = [aSelectedObject objectForKey:kISTRemoteFormsLocalizationNameKey];

and inside another method I am using it. But the issue is that, this is available to me during Object1 lifecycle who created it but not on Object2 lifecycle. How does static work in Objective C.

+2  A: 

AFAIK, what you are calling a class level variable in Objective C is that same as a static global variable in plain ANSI C (which is a strict subset of Objective C).

So you would declare it in your class's .m file, after the imports, but outside of your class interface or implementation, just like any other global variable:

static NSString *mainServiceType = nil;

Then you would have to do your setter (and retain) manually:

if (mainServiceType == nil) {
    mainServiceType = [ [aSelectedObject objectForKey:kMyKey] retain ];
} else { /* etc. */ }

(which may or may not be thread safe, so only use this type of stuff in one thread).

hotpaw2
Excellent. This worked for me. Thank you so much sir.
Abhinav
You can make it thread-safe by using `@synchronized([self class])` (or just `@synchronized(self)` in a class method).
tc.