0

我正在Objective-C中实现教科书单例:

+ (instancetype) sharedSingleton
{
    id sharedInstance = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{            
        sharedInstance = [[self alloc] init];
    });

    return sharedInstance;
}

......就像我已经做了一段时间了。在旧项目(在最新版本的 Xcode 中打开)中将旧的@synchronized-syntax 单例更改为这种类型时,出现错误:

Variable is not assignable (missing __block type specifier)

...指向分配线。我在其他代码的许多部分都有完全相同的代码,在相同的环境下构建和运行,从来没有问题......这是怎么回事?我应该在__block预选赛之前完成并完成它,还是这里有更多的东西?

我唯一能想到的是,我现在正在现代化的这个旧项目还没有过渡到 ARC……(还)

4

1 回答 1

4

您缺少static变量sharedInstance。那条线应该是

static id sharedInstance = nil;

Colin Wheelas 有一篇关于如何使用 dispatch_once 创建单例的简短文章

于 2013-09-16T20:11:28.137 回答