2017-10-06 77 views
1

我節省一定的屬性name核心數據,像這樣..問題與訪問一CoreData屬性

//Saving to CoreData 
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { 
     return 
} 
let managedContext = appDelegate.persistentContainer.viewContext 

let entity = NSEntityDescription.entity(forEntityName: "Category", in: managedContext) 

let category = NSManagedObject(entity: entity!, insertInto: managedContext) 

category.setValue(name, forKeyPath: "theName") 

do { 
try managedContext.save() 
self.mangObjArr.append(category as! Category) 

} catch let error as NSError { 
print("Could not save. \(error), \(error.userInfo)") 
} 

現在我想要得到這個name在另一個視圖控制器,這樣我可以把它作爲一個API調用中的參數。但是,我如何才能獲得我無法弄清楚的名稱屬性。 此外,我不是斯威夫特那麼好,因此問的問題... :)

回答

0

你應該Core Data一些好的教程,因爲這是一個非常基本的問題。在這裏提出問題之前,我認爲您沒有使用Google搜索。我會給你解決方案,但不要再重複一遍。

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Category") 
if let fetchedObjects = try? managedContext.fetch(fetchRequest), !fetchedObjects.isEmpty 
{ 
    let category = fetchedObjects.first as? NSManagedObject 
    print(category?.value(forKey: "theName")) 
} 

鏈接:

https://www.appcoda.com/introduction-to-core-data/

https://www.raywenderlich.com/145809/getting-started-core-data-tutorial

https://code.tutsplus.com/tutorials/core-data-and-swift-managed-objects-and-fetch-requests--cms-25068

+0

謝謝@ PGDev..your答案是非常有益的。還有一個問題(請原諒...... :))。我也從API響應獲得'id'。但是這個ID在xcdatamodel中沒有屬性。那麼我怎麼把它保存在數據庫中?我必須爲這個「ID」做出另一個屬性..?再次感謝... – bws

+0

您必須爲此創建一個新屬性。任何值都將保存在與唯一屬性對應的核心數據中的實體中。 – PGDev

+0

好的...所以你說如果我想保存這個id,我將不得不寫下在問題中提到的coredata方法中的完整保存,然後在你的答案中進行檢索。 。? – bws