objective-c - 在 iOS 应用程序中声明全局变量的最佳做法是什么?

标签 objective-c ios global-variables

假设我有一个 UIColor,我想在每个 View Controller 中使用它来为它的标题/导航栏着色。我想知道申报此类属性(property)的最佳方式是什么。我应该将其声明为应用程序委托(delegate)的成员吗?为全局属性创建一个模型类,并声明一个静态函数+ (UIColor)getTitleColor?将 UIColor 对象传递给每个 View Controller ?有没有我没有描述的另一种方法,它被认为是解决这个问题的最佳方法?

最佳答案

有很多方法可以做到这一点。我喜欢通过在 UIColor 上放置一个类别来做到这一点:

UIColor+MyAppColors.h

@interface UIColor (MyAppColors)

+ (UIColor *)MyApp_titleBarBackgroundColor;

@end

UIColor+MyAppColors.m

#import "UIColor+MyAppColors.h"

@implementation UIColor (MyAppColors)

+ (UIColor *)MyApp_titleBarBackgroundColor {
    static UIColor *color;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        color = [UIColor colorWithHue:0.2 saturation:0.6 brightness:0.7 alpha:1];
    });
    return color;
}

@end

然后我可以通过在任何需要标题栏背景颜色的文件中导入 UIColor+MyAppColors.h 来使用它,并像这样调用它:

myBar.tintColor = [UIColor MyApp_titleBarBackgroundColor];

关于objective-c - 在 iOS 应用程序中声明全局变量的最佳做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12357105/

相关文章:

ios - 仅为一个 tableView 设置行高并忽略 heightForRowAtIndexPath 中的其他 tableView?

ios - numberOfRowsInSection/3 - 只返回 15 张图像而不是 16 或 17,因为它们不能被 3 整除

c++ - 堆还是栈?当在 C++ 中的函数调用中引用常量字符串时

ios - 滚动时在 UITableViewCell 中隐藏 UILabel

iOS 11/12 : How to fetch list of “People Album” from Photos. 应用程序

php - 在其他方法中使用来自 __construct() 的变量

php - 如何在函数php中向数组添加元素

ios - '常数不是有限的!那是非法的。常量 :nan' error in Objective C

ios - 使用 NSDictionary 创建模型对象

ios - BOOL 方法有问题