延迟加载变量错误 [英] Lazy loading variable error
问题描述
我正在编写一个涉及核心数据的程序。我为我的上下文和实体创建了类变量,并且我的代码写成这样:
I am writing a program that involves core data. I created a class variable for my context and entity and have my code written like this:
class PersistencyManager {
var context : NSManagedObjectContext{
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let localContext = appDelegate.managedObjectContext
return localContext
}
var userEntity : NSEntityDescription {
let entity = NSEntityDescription.entityForName(EntityNames.User, inManagedObjectContext: context)
return entity!
}
struct EntityNames {
private static let User = "User"
private static let Category = "Category"
}
}
到目前为止,一切都很好,但我想做的是 em>ly load userEntity
Everything so far works fine, But what I want to do is to "lazy"ly load userEntity
像这样:
lazy var userEntity : NSEntityDescription = {
let entity = NSEntityDescription.entityForName(EntityNames.User, inManagedObjectContext: context)
return entity!
}()
但是当我这样做时, 实例成员上下文不能用于类型Persistency Manager
But when I do, I get an error: "Instance member 'context' cannot be used on type 'Persistency Manager' "
?如何实现我的目标?
What am I doing wrong? How can I achieve my goal?
谢谢!
推荐答案
请尝试 let entity = NSEntityDescription.entityForName(EntityNames.User,inManagedObjectContext:self.context)
使用 self.context
而不是只是上下文
。这在我的操场上。
Note I'm using self.context
instead of just context
. This builds for me in a playground.
这篇关于延迟加载变量错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!