简体   繁体   中英

Class global variables in Objective-C

I'm trying to create variables that can be accessed from any class coming from a Java background I'm struggling to understand this in Objective-C..

in Java we have:

public static int MAIN_MENU = 1, SELECTION_SCREEN = 2;

These can be accessed anywhere like so:

ClassName.MAIN_MENU;

How would do achieve the same thing in its simplest form for Objective-C keeping it within a class?

In Objective-C, classes have no static members. The best I can imagine is creating a getter and setter class method with an utterly ugly global variable:

static T _member = initialValue;

+ (T)someStaticMember
{
    return _member;
}

+ (void)setSomeStaticMember:(T)newVal
{
    _member = newVal;
}

If you only need a getter, ie emulation of a read-only member, then move the static variable inside the function, at least you will have one less global that way.


BUT: if you only need integer constants, why not use an enum ? Or at least some macros?

如果您的目标是仅在自己的类内使用静态变量,则可以在.m文件中声明变量,否则必须使用#define定义全局常量。

#define CONSTANT [ any value ]

  1. You should to use #define MAIN_MENU 1 in header file.
  2. You should to use NSInteger const MAIN_MENU = 1; in m-file and extern NSInteger const MAIN_MENU; in h-file.

And #import this header-file to class you want to use MAIN_MENU

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM