2017-06-20 80 views
-3

我下面的代碼保存在coredata數據庫中的數據。請告訴我什麼是更好的方式來做到這一點。將數據保存在coredata中?

func saveToDB() { 
    if #available(iOS 10, *) { 
     Info = NSEntityDescription.insertNewObject(forEntityName: "Sinfo", into: appDelegate.persistentContainer.viewContext) as! Sinfo 
    } else { 
     Info = NSEntityDescription.insertNewObject(forEntityName: "Sinfo", into: appDelegate.managedObjectContext!) as! Sinfo 
    } 
    info?.title = Comman.shared.title 
    info?.desc = Comman.shared.desc 
    info?.id = String(Utility.shared.currentTimeStamp()) 
    info?.cordinates = Comman.shared.cordinates?.joined(separator: ",") 
    let ocation = Comman.shared.location 
    info?.city = location?.city 
    info?.state = location?.state 
    info?.country = location?.country 
    info?.state = location?.state 
    info?.zip = location?.pincode 
    info?.isuploaded = false 
    appDelegate.saveContext() 
} 
+0

這將更適合於[代碼評論](https://codereview.stackexchange.com)。 –

+0

至少有一個更好的方法是使用更少的問號;-)並且Swift是區分大小寫的。 – vadian

回答

0

沒有理由使用persistentContainer,你是不是ios 10和以上只。只需創建一個工作和使用它的堆棧。 PersistentContainer有助於不必創建核心數據堆棧,但是如果您正在創建核心數據堆棧,則無法使用它。

0

您可以像使用

設情境=(UIApplication.shared.delegate爲AppDelegate中!).persistentContainer.viewContext

讓newcontact = NSEntityDescription.insertNewObject(forEntityName: 「僱員」,分爲:上下文)作爲NSManagedObject

newcontact.setValue(txtempid.text, forKey: "emp_id"); 
    newcontact.setValue(txtempname.text, forKey: "emp_name"); 
    newcontact.setValue(txtempadd.text, forKey: "emp_add"); 

    do 
    { 
     try context.save() 
    } 
    catch 
    { 

    } 
+0

我可以使用NSManaged子類來達到這個目的嗎? – Techiee