Created
October 28, 2017 15:13
-
-
Save Callonski/b33e60c2c0ee857451354835fad74610 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import CoreData | |
var people: [NSManagedObject] = [] | |
func deleteFromCD() | |
{ | |
guard let appDelegate = | |
UIApplication.shared.delegate as? AppDelegate else { | |
return | |
} | |
let managedContext = appDelegate.persistentContainer.viewContext | |
let firstPerson = people[0] | |
managedContext.delete(firstPerson) | |
do { | |
try managedContext.save() | |
} catch { | |
let saveError = error as NSError | |
print(saveError) | |
} | |
} | |
func loadFromCD() | |
{ | |
guard let appDelegate = | |
UIApplication.shared.delegate as? AppDelegate else { | |
return | |
} | |
let managedContext = appDelegate.persistentContainer.viewContext | |
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person") | |
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) | |
let sortDescriptors = [sortDescriptor] | |
fetchRequest.sortDescriptors = sortDescriptors | |
let resultPredicate = NSPredicate(format: "name = 'Bill'") | |
fetchRequest.predicate = resultPredicate | |
do { | |
people = try managedContext.fetch(fetchRequest) | |
} catch let error as NSError { | |
print("Could not fetch. \(error), \(error.userInfo)") | |
} | |
} | |
func saveToCD() | |
{ | |
guard let appDelegate = | |
UIApplication.shared.delegate as? AppDelegate else { | |
return | |
} | |
let managedContext = appDelegate.persistentContainer.viewContext | |
let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)! | |
let person = NSManagedObject(entity: entity, insertInto: managedContext) | |
person.setValue("Apa", forKeyPath: "name") | |
do { | |
try managedContext.save() | |
people.append(person) | |
} catch let error as NSError { | |
print("Could not save. \(error), \(error.userInfo)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment