Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- `func retrieveAllContact()->[Contact]{`
- `let appDelegate = (UIApplication.shared.delegate) as! AppDelegate`
- `let context = appDelegate.persistentContainer.viewContext`
- `var contact:[NSManagedObject] = []`
- `var contactList:[Contact] = []`
- `let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CDContact")`
- `do {`
- `contact = try context.fetch(fetchRequest)`
- `for c in contact {`
- `let firstname = c.value(forKey: "firstname") as? String`
- `let lastname = c.value(forKey: "lastname") as? String`
- `let mobileno = c.value(forKey: "mobileno") as? String`
- `contactList.append(Contact(firstname: firstname!, lastname: lastname!, mobileno: mobileno!))`
- `print("\(firstname!) \(lastname!), \(mobileno!)")`
- `}`
- `} catch let error as NSError {`
- `print ("Could not fetch. \(error), \(error.userInfo)")`
- `}`
- `return contactList`
- `}`
- `func updateContact(mobileno: String, newContact:Contact){`
- `let appDelegate = (UIApplication.shared.delegate) as! AppDelegate`
- `let context = appDelegate.persistentContainer.viewContext`
- `var contact:[NSManagedObject] = []`
- `let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CDContact")`
- `do {`
- `contact = try context.fetch(fetchRequest)`
- `for c in contact {`
- `if (c.value(forKey: "mobileno") as? String == mobileno){`
- `c.setValue(newContact.firstName, forKey: "firstname")`
- `c.setValue(newContact.lastName, forKey: "lastname")`
- `c.setValue(newContact.mobileNo, forKey: "mobileno")`
- `}`
- `}`
- `} catch let error as NSError {`
- `print ("Could not fetch. \(error), \(error.userInfo)")`
- `}`
- `do {`
- `try context.save()`
- `} catch let error as NSError {`
- `print ("Could not fetch. \(error), \(error.userInfo)")`
- `}`
- `}`
- `func deleteContact(mobileno: String){`
- `let appDelegate = (UIApplication.shared.delegate) as! AppDelegate`
- `let context = appDelegate.persistentContainer.viewContext`
- `var contact:[NSManagedObject] = []`
- `let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CDContact")`
- `do {`
- `contact = try context.fetch(fetchRequest)`
- `for c in contact {`
- `if (c.value(forKey: "mobileno") as? String == mobileno){`
- `context.delete(c)`
- `}`
- `}`
- `} catch let error as NSError {`
- `print ("Could not fetch. \(error), \(error.userInfo)")`
- `}`
- `do {`
- `try context.save()`
- `} catch let error as NSError {`
- `print ("Could not fetch. \(error), \(error.userInfo)")`
- `}`
- `}`
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement