Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.81 KB | None | 0 0
  1. func getContext () -> NSManagedObjectContext {
  2. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  3. return appDelegate.persistentContainer.viewContext
  4. }
  5.  
  6. func storePersonInfo (identification: Int, surname: String, givenName: String, dateOfBirth: Date) {
  7. let context = getContext()
  8.  
  9. //retrieve the entity that we just created
  10. let entity = NSEntityDescription.entity(forEntityName: "Person", in: context)
  11.  
  12. let transc = NSManagedObject(entity: entity!, insertInto: context)
  13.  
  14. //set the entity values
  15. transc.setValue(identification, forKey: "identification")
  16. transc.setValue(surname, forKey: "surname")
  17. transc.setValue(givenName, forKey: "givenName")
  18. transc.setValue(dateOfBirth, forKey: "dateOfBirth")
  19.  
  20. //save the object
  21. do {
  22. try context.save()
  23. print("saved!")
  24. } catch let error as NSError {
  25. print("Could not save \(error), \(error.userInfo)")
  26. } catch {
  27.  
  28. }
  29. }
  30.  
  31. func getPersonInfo () -> String {
  32. var info = ""
  33. let dateFormatter = DateFormatter()
  34. dateFormatter.dateFormat = "dd-MM-yyyy"
  35.  
  36. //create a fetch request, telling it about the entity
  37. let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
  38.  
  39. do {
  40. //go get the results
  41. let searchResults = try getContext().fetch(fetchRequest)
  42.  
  43. //I like to check the size of the returned results!
  44. print ("num of results = \(searchResults.count)")
  45.  
  46. //You need to convert to NSManagedObject to use 'for' loops
  47. for trans in searchResults as [NSManagedObject] {
  48. let id = String(trans.value(forKey: "identification") as! Int)
  49. let surname = trans.value(forKey: "surname") as! String
  50. let givenName = trans.value(forKey: "givenName") as! String
  51. let strDate = dateFormatter.string(from: trans.value(forKey: "dateOfBirth") as! Date)
  52. info = info + id + ", " + givenName + " " + surname + ", " + strDate + "\n"
  53. }
  54. } catch {
  55. print("Error with request: \(error)")
  56. }
  57. return info;
  58. }
  59.  
  60. func removeRecords () {
  61. let context = getContext()
  62. // delete everything in the table Person
  63. let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
  64. let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
  65.  
  66. do {
  67. try context.execute(deleteRequest)
  68. try context.save()
  69. } catch {
  70. print ("There was an error")
  71. }
  72. }
  73.  
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement