2017-10-29 142 views
0

對於我的生活我無法弄清楚爲什麼我沒有得到任何保存到CoreData的東西。我在構建階段添加了CoreData.framework,但在查看Model.sqlite時仍然沒有任何結果。CoreData不存儲Swift 4 Xcode 9

的AppDelegate

lazy var persistentContainer: NSPersistentContainer = { 

    let container = NSPersistentContainer(name: "Model") 
    container.loadPersistentStores(completionHandler: { 
     (storeDescription, error) in 

     if let error = error as NSError? { 
      fatalError("Unresolved error \(error), \(error.userInfo)") 
     } 
    }) 
    return container 
}() 

func saveContext() { 
    let context = persistentContainer.viewContext 
    if context.hasChanges { 
     do { 
      try context.save() 
     } catch { 
      let nserror = error as NSError 
      fatalError("Unresolved error \(nserror), \(nserror.userInfo)") 
     } 
    } 
} 

然後在我MainViewController

var timer : Timer? 
var distance = Measurement(value: 0, unit: UnitLength.meters) 
var run: Run! //name of the entity 
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 

// ...

private func saveRun() { 
    print("saveRun") 
    let newRun = Run(context: context) 
    print("got past core data") 
    newRun.distance = distance.value 
    newRun.duration = Int16(seconds) 
    newRun.timestamp = Date() 

    for locations in locationList { 
     let locationObject = Location(context: context) 
     locationObject.timestamp = locations.timestamp 
     locationObject.latitude = locations.coordinate.latitude 
     locationObject.longitude = locations.coordinate.longitude 
     newRun.addToLocations(locationObject) 

     (UIApplication.shared.delegate as! AppDelegate).saveContext() 

     run = newRun 
    } 
} 
+0

你應該叫'context.save()'然後工作 – Mannopson

+0

原諒我的無知如我在這個真正的新但是,這不是什麼有發生( UIApplication.shared.delegate as!AppDelegate).saveContext() –

+0

有沒有錯誤?只是數據沒有被保存? – 3stud1ant3

回答

0

所以......我是個白癡。它與我發佈的代碼一起工作。擰緊是在我的代碼中出現錯誤,不知道如何正確使用Liya。謝謝大家的幫助

@Francesco Deliro

有用的事情。我會記住這一點

感謝大家的幫助

0

核心數據預計將在單個線程上運行。儘管該線程不一定是主線程,但Core Data並不旨在從不同線程訪問。