目标C - 静态和全局变量? [英] Objective C - Static and global variable?

查看:114
本文介绍了目标C - 静态和全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在名为Ad的类的.m文件中,我有3个静态字符串

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";

我可以简单地在当前类中使用这些静态变量,但是我无法从其他任何类中调用它们,有没有办法让这些静态变量全局?
因此,例如在我的viewcontroller类中,我可以做类似的事情。

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
}


推荐答案

您可以将以下声明添加到您的HomeViewController.h头文件中,然后需要将其导入任何想要访问字符串的位置。

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;

然后修改您的定义以删除'static'。

Then alter your definitions to remove 'static'.

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

如果您不希望字符串的用户必须导入HomeViewController.h,那么您可以也只是在AdState.h中定义这些字符串,并将这些定义放入AdState.m中(并将其从HomeViewController.m中移除),之后字符串的用户只需导入AdState.h即可使用字符串。

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.

这篇关于目标C - 静态和全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆