【发布时间】:2021-12-13 22:57:16
【问题描述】:
您好,我是目标 c 的新手。我在目标 c 中创建了一个类别。我使用dispatch_once 来定义自定义 UIColor。
检查下面的代码。
#import "UIColor+CustomColors.h"
@implementation UIColor (CustomColors)
- (UIColor *)GetCustomColorLightYellowBGColor {
static UIColor *lightYellowBGColor;
//use dispatch_once_t pointer predicate to check if the block has finished
//A pointer to a dispatch_once_t structure that is used to test whether the block has completed or not
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
lightYellowBGColor = [UIColor colorWithRed:244.0 / 255.0
green:230.0 / 255.0
blue:54.0 / 255.0
alpha:1.0];
});
return lightYellowBGColor;
}
@end
https://developer.apple.com/documentation/dispatch/1447169-dispatch_once 的 dispatch_once 文档提到以下内容
此函数对于在应用程序中初始化全局数据(单例)很有用。在使用或测试由块初始化的任何变量之前,请始终调用此函数。
所以我初始化了自定义 UIColor 类,然后我使用了
self.view.backgroundColor = customColorClass.CustomColorLightYellowBGColor;
视图上的颜色会正确更改,因此一切正常。
我想问以下问题。
如果我故意再次使用self.view.backgroundColor = customColorClass.GetCustomColorLightYellowBGColor;
dispatch_once 会再次初始化 UIColor,还是因为单例初始化不会初始化 UIColor?任何帮助表示赞赏。
【问题讨论】:
标签: ios objective-c objective-c-category