【问题标题】:Objective c global variables like width and height sharing for all view controllers目标 c 全局变量,如所有视图控制器的宽度和高度共享
【发布时间】:2026-01-20 08:45:02
【问题描述】:

我想为所有视图控制器定义一些特定的尺寸,例如用于自动布局的宽度或高度。我可以创建一个头文件,然后包含一次,以便我可以为每个视图控制器使用存储在该头文件中的变量吗?

【问题讨论】:

  • 你能加点努力吗?

标签: objective-c uiviewcontroller global-variables


【解决方案1】:

如果它们不应该改变,你应该将它们声明为常量。否则,您通常应该避免使用全局变量。通常有更好的方法来完成同样的事情。

NSUInteger const THE_ANSWER = 42;

如果你必须使用变异全局变量,你应该将它们声明为 extern。

extern NSUInteger theChangingAnswer;

确保在某个源文件中定义它们。

NSUInteger theChangingAnswer = 42;

【讨论】:

    【解决方案2】:

    一个棘手的方法是为您的大小常量定义一个类别。

    @interface UIViewController (MySizeConstants)
        @property (readonly, nonatomic) CGFloat mySizeConstantHeight;
        @property (readonly, nonatomic) CGFloat mySizeConstantWidth;
    @end
    
    @implementation UIViewController (MySizeConstants)
        - (CGFloat)mySizeConstantHeight { return 42.0; }
        - (CGFloat)mySizeConstantWidth { return 6 * 9.0; }
    @end
    

    (唯一?)优点是您不需要使用 PCH 或导入到每个视图控制器中。缺点比较多,但我喜欢提出不同的思考问题的方式。

    【讨论】:

      【解决方案3】:

      听起来您需要的是Precompiled Header!这是一个自动导入到您所有文件中的文件。您可以定义全局变量并在项目的所有文件中访问它们。

      前几次设置起来很棘手,但最终变得非常容易。 Here's an answer 在堆栈上,指导您完成操作。

      Here's some codehighly recommend 包含在您的 .pch 文件中:

      #ifdef DEBUG
        #define DLog(...) NSLog(@"%s %@", __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__])
        #define ALog(...) [[NSAssertionHandler currentHandler] handleFailureInFunction:[NSString stringWithCString:__PRETTY_FUNCTION__ encoding:NSUTF8StringEncoding] file:[NSString stringWithCString:__FILE__ encoding:NSUTF8StringEncoding] lineNumber:__LINE__ description:__VA_ARGS__]
      #else
        #define DLog(...) do { } while (0)
        #ifndef NS_BLOCK_ASSERTIONS
          #define NS_BLOCK_ASSERTIONS
        #endif
        #define ALog(...) NSLog(@"%s %@", __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__])
      #endif
      
      #define ZAssert(condition, ...) do { if (!(condition)) { ALog(__VA_ARGS__); }} while(0)
      
      // delegate
      #define UIAppDelegate (AppDelegate *)[[UIApplication sharedApplication] delegate]
      #define APPDELEGATE   ((AppDelegate *)[[UIApplication sharedApplication] delegate])
      
      // system
      #define IS_IPHONE_4INCH (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone && [UIScreen mainScreen].bounds.size.height==568)
      #define IS_IPAD                     (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
      
      // screen size
      #define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
      #define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
      #define IS_IPHONE_4 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 480.0)
      #define IS_IPHONE_5 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 568.0)
      #define IS_IPHONE_6 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 667.0)
      #define IS_IPHONE_6PLUS (IS_IPHONE && [[UIScreen mainScreen] nativeScale] == 3.0f)
      #define IS_IPHONE_6_PLUS (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 736.0)
      #define IS_RETINA ([[UIScreen mainScreen] scale] >= 2.0)
      #define IS_RETINA_DISPLAY ([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)] && ([UIScreen mainScreen].scale >= 2.0))
      #define IS_PORTRAIT                 UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])
      #define IS_LANDSCAPE                UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])
      
      //system version
      #define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
      #define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
      
      // math
      #define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
      #define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))
      
      // cores
      #define RGB(r,g,b)    [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]
      #define RGBA(r,g,b,a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:a]
      #define MAKECOLOR(R, G, B, A) [UIColor colorWithRed:((float)R/255.0f) green:((float)G/255.0f) blue:((float)B/255.0f) alpha:A]
      #define MAKECOLORFROMHEX(hexValue) [UIColor colorWithRed: ((float)((hexValue & 0xFF0000) >> 16))/255.0 green:((float)((hexValue & 0xFF00) >> 8))/255.0 blue:((float)(hexValue & 0xFF))/255.0 alpha:1.0]
      
      
      
      //customizations
      #define SHOW_STATUS_BAR               [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
      #define HIDE_STATUS_BAR               [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
      
      #define SHOW_NAVIGATION_BAR           [self.navigationController setNavigationBarHidden:FALSE];
      #define HIDE_NAVIGATION_BAR           [self.navigationController setNavigationBarHidden:TRUE];
      
      #define VC_OBJ(x) [[x alloc] init]
      #define VC_OBJ_WITH_NIB(x) [[x alloc] initWithNibName : (NSString *)CFSTR(#x) bundle : nil]
      
      #define RESIGN_KEYBOARD [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
      
      #define CLEAR_NOTIFICATION_BADGE                       [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
      #define REGISTER_APPLICATION_FOR_NOTIFICATION_SERVICE  [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)]
      
      #define HIDE_NETWORK_ACTIVITY_INDICATOR                 [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
      #define SHOW_NETWORK_ACTIVITY_INDICATOR                 [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
      

      【讨论】:

      • 不相关,但您的 IS_RETINA 宏将在 iPhone 6+/6s+ 上失败。你应该很少使用这两个SYSTEM_VERSION_xxx 宏。