开发者

Objective C - Static and global variable?

In my .m file for a class named Ad , I have 3 static strings

static NSString *AdStateDisabled = @"disable";
static NSString *AdStateExpired = @"expired";
static 开发者_如何学编程NSString *AdStateActive = @"active";

I can simply use these static variables in the current class, but i cannot call them from any other class, is there a way to make these static variables global? So for example in my viewcontroller class i can do something like.

//HomeViewController.m
if ([self.ad.state isEqual:Ad.AdStateDisabled])
{
     //do something
}


You could add the following declarations to your HomeViewController.h header, which would then need to be imported anywhere you wanted access to the strings.

//HomeViewController.h
extern NSString *AdStateDisabled;
extern NSString *AdStateExpired;
extern NSString *AdStateActive;

Then alter your definitions to remove 'static'.

//HomeViewController.m
NSString *AdStateDisabled = @"disable";
NSString *AdStateExpired = @"expired";
NSString *AdStateActive = @"active";

If you don't want a user of the strings to have to import HomeViewController.h then you could also just define those strings in AdState.h and put the definitions into AdState.m (and remove them from HomeViewController.m) after which users of the string would just need to import AdState.h to use the strings.


First, remove the static. Static variables and functions in C and Objective-C mean that they're visible only to the current compilation unit (that is more or less: only the file that you've declared the statix variable in can see it).

Next, you also need to declare the variables in a public header file with "extern", like the one of the class associated with the class:

extern NSString *AdStateDisabled;

You can then use them in other files as well, but you would not access them as "Ad.AdStateDisabled" but just as "AdStateDisabled".


From the looks of it, it seems you're trying to create some kind of "string based enumerator" for your state types. Happy to report that Obj-C now provides means to do that nicely:

In your header file, add the following declarations:

typedef NSString *AdState NS_TYPED_ENUM;
extern AdState const AdStateDisabled;
extern AdState const AdStateExpired;
extern AdState const AdStateActive;

And in the .m file, add the following definitions:

AdState const AdStateDisabled = @"disable"
AdState const AdStateExpired = @"expired";
AdState const AdStateActive = @"active";

You can then use these constants and even enumerate over them using for loops and so on. You will need to import this header in every source you intend to use these constants in, so you may create some "common.h" header for infrastructure, and tell the target to use it as "precompiled header" or the like.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜