我正在尝试使用单例进行核心数据.以前,我已经成功地通过创建一个类CoreDataStack.h / .m,调用下面的默认堆栈方法,以及它在Objective-C中的相应托管对象上下文,并且运行良好: //RETURNS Core
//RETURNS CoreDataStack
+ (instancetype)defaultStack {
static CoreDataStack *defaultStack;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
defaultStack = [[self alloc]init];
});
return defaultStack;
}
但是,我正在使用Swift项目,我一直在努力将其转换为最新的Swift语法.我该怎么做呢?这是我到目前为止的尝试:
class func defaultStack() -> Self {
var defaultStack: CoreDataStack
var onceToken: dispatch_once_t = 0
dispatch_once(&onceToken) {
defaultStack = self.init()
}
return defaultStack
}
和我的Xcode生成错误:

class CoreDataStack {
// Here you declare all your properties
static let sharedInstance = User()
private init() {
// If you have something to do at the initialization stage
// you can add it here. It will only be called once. Guaranteed.
}
// Add the rest of your methods here
}
您将把您的方法和属性称为CoreDataStack.sharedInstance().property和CoreDataStack.sharedInstance().method().我建议使用更短的而不是sharedInstance,比如服务.
此解决方案通常适用于您的Core Data案例.
