`Synchronized` 在 XCTest 中不起作用

`Synchronized` not working in XCTest

我有一个包含 cocoapod 的应用程序,其中包含应用程序背后的引擎。在这个 cocoapod 中,我有一个基本 class.

的共享实例
+ (Restaurant *)current {
    @synchronized(self) {
        if (current == nil) {
            current = [[Restaurant alloc] initWithId:0];
        }
    }
    return current;
}

现在,我正在 运行 对我的应用程序中的一些其他代码进行一些单元测试。看起来像这样:

- (void)testPOSTCodeGeneration {
    [[Restaurant current] setMainTable:4];

    NSLog(@"Main table in test: %d", [[Restaurant current] mainTable]);

    Generator *generator = [[Generator alloc] init];

    XCTAssertEqualObjects([[Restaurant current] mainTable], generator.table);
}

Generator.m 中,我按照以下方式做了一些事情:

- (void)init {
    ...
    self.table = [[Restaurant current] mainTable];
    ...
}

奇怪的是,这个测试失败了。 mainTable 的默认值为 0,除非设置了不同的数字。所以即使我将它设置为 4(并且 Main table in test: 记录 4),它 returns 0。@synchronized 与 Xcode 单元测试不兼容吗?或者有人知道这里发生了什么吗?

mainTable不是对象,所以不要调用XCTAssertEqualObjects。而是使用 XCTAssertEquals.

Apple 建议使用 dispatch_once 而不是同步,所以你可以试试这个代码:

+ (Restaurant *)current {
    static Restaurant *current=nil:
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
       current = [[Restaurant alloc] initWithId:0];
    }
    return current;
}

Link 苹果文档:https://developer.apple.com/reference/dispatch/1447169-dispatch_once