【问题标题】:Lazy loading variable error延迟加载变量错误
【发布时间】:2016-05-04 20:08:51
【问题描述】:

我正在编写一个涉及核心数据的程序。我为我的 contextentity 创建了一个类变量,并且我的代码是这样写的:

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"
    }
}

到目前为止一切正常,但我想做的是“lazy”加载 userEntity

像这样:

   lazy var userEntity : NSEntityDescription = {
        let entity = NSEntityDescription.entityForName(EntityNames.User, inManagedObjectContext: context)
        return entity!

    }()

但是当我这样做时,我得到一个错误:“Instance member 'context' cannot be used on type 'Persistency Manager'”

我做错了什么?我怎样才能实现我的目标?

谢谢!

【问题讨论】:

    标签: swift core-data computed-properties


    【解决方案1】:

    试试let entity = NSEntityDescription.entityForName(EntityNames.User, inManagedObjectContext: self.context)

    请注意,我使用的是self.context 而不仅仅是context。这是在操场上为我构建的。

    【讨论】:

    • = {...}() 语法用于为复杂的初始化序列定义(然后执行)代码块。
    • @DavidBerry 谢谢,你是对的 - 正在考虑一个不同的问题。更新了我的答案。
    • 我想现在明白了。问题是匿名代码块在不指定 self 的情况下不会自动访问实例变量,而不是错误消息提供了任何线索。
    • 正确 - 实例变量未在闭包范围内被捕获。
    • 谢谢!这解决了我的问题。现在一切都说得通了。
    猜你喜欢
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多