Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.06 KB | None | 0 0
  1. `func retrieveAllContact()->[Contact]{`
  2. `let appDelegate = (UIApplication.shared.delegate) as! AppDelegate`
  3. `let context = appDelegate.persistentContainer.viewContext`
  4. `var contact:[NSManagedObject] = []`
  5. `var contactList:[Contact] = []`
  6.  
  7. `let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CDContact")`
  8. `do {`
  9. `contact = try context.fetch(fetchRequest)`
  10.  
  11. `for c in contact {`
  12. `let firstname = c.value(forKey: "firstname") as? String`
  13. `let lastname = c.value(forKey: "lastname") as? String`
  14. `let mobileno = c.value(forKey: "mobileno") as? String`
  15. `contactList.append(Contact(firstname: firstname!, lastname: lastname!, mobileno: mobileno!))`
  16. `print("\(firstname!) \(lastname!), \(mobileno!)")`
  17. `}`
  18. `} catch let error as NSError {`
  19. `print ("Could not fetch. \(error), \(error.userInfo)")`
  20. `}`
  21. `return contactList`
  22. `}`
  23.  
  24. `func updateContact(mobileno: String, newContact:Contact){`
  25. `let appDelegate = (UIApplication.shared.delegate) as! AppDelegate`
  26. `let context = appDelegate.persistentContainer.viewContext`
  27. `var contact:[NSManagedObject] = []`
  28. `let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CDContact")`
  29. `do {`
  30. `contact = try context.fetch(fetchRequest)`
  31.  
  32. `for c in contact {`
  33. `if (c.value(forKey: "mobileno") as? String == mobileno){`
  34. `c.setValue(newContact.firstName, forKey: "firstname")`
  35. `c.setValue(newContact.lastName, forKey: "lastname")`
  36. `c.setValue(newContact.mobileNo, forKey: "mobileno")`
  37. `}`
  38. `}`
  39. `} catch let error as NSError {`
  40. `print ("Could not fetch. \(error), \(error.userInfo)")`
  41. `}`
  42.  
  43. `do {`
  44. `try context.save()`
  45. `} catch let error as NSError {`
  46. `print ("Could not fetch. \(error), \(error.userInfo)")`
  47. `}`
  48. `}`
  49.  
  50. `func deleteContact(mobileno: String){`
  51. `let appDelegate = (UIApplication.shared.delegate) as! AppDelegate`
  52. `let context = appDelegate.persistentContainer.viewContext`
  53. `var contact:[NSManagedObject] = []`
  54. `let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CDContact")`
  55. `do {`
  56. `contact = try context.fetch(fetchRequest)`
  57.  
  58. `for c in contact {`
  59. `if (c.value(forKey: "mobileno") as? String == mobileno){`
  60. `context.delete(c)`
  61. `}`
  62. `}`
  63. `} catch let error as NSError {`
  64. `print ("Could not fetch. \(error), \(error.userInfo)")`
  65. `}`
  66.  
  67. `do {`
  68. `try context.save()`
  69. `} catch let error as NSError {`
  70. `print ("Could not fetch. \(error), \(error.userInfo)")`
  71. `}`
  72. `}`
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement