-1

I want a static varibale in .h of a class and want it to be inherited to its child class.

@interface :UIViewController
static bool isSearchWindowOpen ; //something like this.
@end

If i write like :

static bool isSearchWindowOpen ; 
@interface :UIViewController
    @end

it works fine but cannot be inherited by child classes.

pls suggest.

LUI
  • 85
  • 1
  • 9
  • What's the colon in the interface declaration? What do you mean by "inherit"? Do you want to make the variable visible or do you want to have each (sub-) class refer to its own variable? It's not clear what you are trying to achieve. – Nikolai Ruhe Mar 04 '14 at 10:06

2 Answers2

1

This sounds a bit like you are confusing this with some other programming language, like C++. In Objective-C, just like C, a static variable is a variable with file scope. If you declare a static variable in a header file, then any source file including that header file has its own copy of the static variable.

You'd probably want a class method

+ (BOOL)isSearchWindowOpen

with implementation

static BOOL sSearchWindowOpen;
+ (void)setSearchWindowOpen:(BOOL)open { sSearchWindowOpen = open; }
+ (BOOL)isSearchWindowOpen { return sSearchWindowOpen; }

Probably even better to write code that checks whether the search window is open, instead of relying on a static variable that you have to track correctly all the time.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
0

The variable as declared has nothing to do with the class. It’s a global static in the “C sense”: only code in the same file can access it. (See Wikipedia for details.) You can write class accessors:

static BOOL foo;

+ (void) setFoo: (BOOL) newFoo
{
    foo = newFoo;
}

That way the class descendants can access the variable, too. But it’s not a good idea anyway. What problem are you trying to solve?

zoul
  • 102,279
  • 44
  • 260
  • 354