【问题标题】:What is the best practice for declaring a global variable in an iOS app?在 iOS 应用程序中声明全局变量的最佳做法是什么?
【发布时间】:2012-09-10 18:02:57
【问题描述】:
假设我有一个UIColor,我想在每个视图控制器中使用它来为它的标题/导航栏着色。我想知道声明此类财产的最佳方式是什么。我应该将其声明为应用程序委托的成员吗?为全局属性创建一个模型类,并声明一个静态函数+ (UIColor)getTitleColor?将UIColor 对象传递给每个视图控制器?有没有我没有描述的另一种方法,被认为是解决这个问题的最佳方法?
【问题讨论】:
标签:
objective-c
ios
global-variables
【解决方案1】:
有很多方法可以做到这一点。我喜欢通过在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];
【解决方案2】:
根据您正在尝试做的事情,我认为您可以通过使用外观更轻松地做到这一点。您可以为所有不同类型的界面元素分配不同的颜色。更多信息请查看the UIAppearance protocol。
如果这不是您想要的,那么我建议@rob mayoff 回答:使用类别。