- OC 中不允许编译时初始化变量, 静态变量和全局变量, 只能赋值常量, 所以只能通过
dispatch_once_t
来避免多线程多次初始化问题.
static NSString *a = @"asdf";
static int b = 10;
static NSString *c = [[NSString alloc] init]; /// Initializer element is not a compile-time constant
@implementation AAA
+ (id)shared{
static AAA * staticInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
staticInstance = [[self alloc] init];
});
return staticInstance;
}
@end
- ObjectiveC++ 允许编译时初始化变量, 所以不需要处理线程问题
@interface AA : NSObject
@end
@implementation AA
- (instancetype)init
{
self = [super init];
if (self) {
NSLog(@"init");
}
return self;
}
@end
static AA *aa = [[AA alloc] init];
- Swift 允许编译时初始化变量, 所以不需要处理线程问题
class MyClass {
static let shared = MyClass()
private init() {
print("init")
sleep(10)
}
}
DispatchQueue.global().async {
for _ in 0 ..< 100 {
DispatchQueue.global().async {
_ = MyClass.shared
print(Thread.current)
}
}
}
网友评论