Jos*_*nor 3 singleton core-data ios swift
我正在尝试使用单例进行核心数据.以前,我已经成功地通过CoreDataStack.h/.m在Objective-C中创建一个类,调用下面的默认堆栈方法及其各自的托管对象上下文,并且非常有效:
//RETURNS CoreDataStack
+ (instancetype)defaultStack {
static CoreDataStack *defaultStack;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
defaultStack = [[self alloc]init];
});
return defaultStack;
}
Run Code Online (Sandbox Code Playgroud)
但是,我正在使用Swift项目,我一直在努力将其转换为最新的Swift语法.我该怎么做呢?这是我到目前为止的尝试:
class func defaultStack() -> Self {
var defaultStack: CoreDataStack
var onceToken: dispatch_once_t = 0
dispatch_once(&onceToken) {
defaultStack = self.init()
}
return defaultStack
}
Run Code Online (Sandbox Code Playgroud)
和我的Xcode生成错误:
要创建单例,请使用Krakendev的单行单例代码:
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
}
Run Code Online (Sandbox Code Playgroud)
您将把您的方法和属性称为CoreDataStack.sharedInstance().property和CoreDataStack.sharedInstance().method().我推荐使用更短的东西而不是sharedInstance像service.
此解决方案通常适用于您的Core Data案例.
| 归档时间: |
|
| 查看次数: |
1506 次 |
| 最近记录: |