2016-07-12 19 views
2

我的變量entityDescription似乎是零,所以編譯時有一個致命錯誤。有誰知道解決方案? persistentContainer在同一個類中聲明(AppDelegate)。NSEntityDescription是無

let entityDescription = NSEntityDescription.entity(forEntityName: "Person", in: self.persistentContainer.viewContext) 
let newPerson = NSManagedObject(entity: entityDescription!, insertInto: self.persistentContainer.viewContext) 
newPerson.setValue("Thomas", forKey: "first") 

回答

2

您應該看看Core Data Xcode模板。 (選擇新項目,檢查,主/細節,檢查覈心數據。)在Swift 3中,您可以像使用有效的託管對象上下文一樣創建一個新對象。

let newPerson = Person(context: context) 
newPerson.first = "Thomas" 
+0

這僅適用於iOS的10,下面是你應該檢查阿倫EA的響應版本:http://stackoverflow.com/a/38344166/2452039 –

+0

沒有,API語法不同的是,原則在多年前的Core Data早期版本中是一樣的。 – Mundi

4

請檢查方法名稱,下面的代碼爲我創建一個NSEntityDescription對象。

let desc:NSEntityDescription? = NSEntityDescription.entityForName("Person", inManagedObjectContext: self.managedObjectContext); 
print(desc) 
相關問題