Lazy loading variable error

社会主义新天地 提交于 2019-12-02 13:31:54

问题


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

Everything so far works fine, But what I want to do is to "lazy"ly load userEntity

Like this :

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

    }()

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?

Thank you!


回答1:


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

Note I'm using self.context instead of just context. This builds for me in a playground.



来源:https://stackoverflow.com/questions/35044730/lazy-loading-variable-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!