【问题标题】:Saving data in coredata? [closed]在 coredata 中保存数据? [关闭]
【发布时间】:2017-11-22 21:23:59
【问题描述】:

我在下面的代码中将数据保存在 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()
}

【问题讨论】:

  • 这更适合Code Review
  • 至少更好的方法是使用更少的问号 ;-) 并且 Swift 区分大小写。

标签: ios iphone swift xcode core-data


【解决方案1】:

你可以用喜欢

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

let newcontact = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: context) as 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 {
}

【讨论】:

  • 我可以为此目的使用 NSManaged 子类吗?
【解决方案2】:

没有理由使用persistentContainer,因为你不是只有ios 10 及更高版本。只需创建一个有效的堆栈并使用它。 PersistentContainer 有助于不必创建核心数据堆栈,但如果您要创建一个,那么使用它真的没有意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    相关资源
    最近更新 更多