Lazy loading variable error

2019-03-01 03:53发布

问题:

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.