[英]value of type AppDelegate has no member managedObjectContext
[英]Value of type 'AppDelegate' has no member 'managedObjectContext'
func saveName(name: String){
//1
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
//2
let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)
//3
person.setValue(name, forKey: "name")
//4
var error: NSError?
if !managedContext.save(&error) {
print("Could not save \(error!), \(String(describing: error?.userInfo))");
}
//5
people.append(person)
}
我無法使該程序正常運行。 我正在嘗試保存到CoreData。
在Swift 3中 ,您可以像這樣訪問上下文對象:
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
由於經常使用托管對象上下文,因此在AppDelegate
添加了惰性實例化屬性
lazy var managedObjectContext : NSManagedObjectContext = {
return self.persistentContainer.viewContext
}()
entity
和managedObjectContext
都應該是非可選的。
在代碼中更改第二行以訪問托管對象上下文
let managedContext = appDelegate.persistantContainer.Viewcontext
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.