How to use global variables in Objective-C?

前端 未结 4 695
谎友^
谎友^ 2020-12-05 10:58

How should I declare a global variable in my Objective-C project?

4条回答
  •  被撕碎了的回忆
    2020-12-05 11:03

    Don't. Global variables are often a sign of poor design. A common replacement in Objective-C is a class method that returns an object (that may or may not be a singleton), such as [NSUserDefaults standardUserDefaults] or [UIDevice currentDevice].

    However, if you must use a global variable, read on.

    In your header:

    extern NSString *someString;
    extern NSInteger someInteger;
    

    In your implementation file:

    NSString *someString = @"DEFAULT_VALUE";
    NSInteger someInteger = DEFAULT_VALUE;
    

提交回复
热议问题