Skip to content

Instantly share code, notes, and snippets.

@softwarejc
Created Feb 13, 2016
Embed
What would you like to do?
PersonService.swift
import CoreData
class PersonService{
var context: NSManagedObjectContext
init(context: NSManagedObjectContext){
self.context = context
}
// Creates a new Person
func create(name: String, age: NSNumber) -> Person {
let newItem = NSEntityDescription.insertNewObjectForEntityForName(Person.entityName, inManagedObjectContext: context) as! Person
newItem.name = name
newItem.age = age
return newItem
}
// Gets a person by id
func getById(id: NSManagedObjectID) -> Person? {
return context.objectWithID(id) as? Person
}
// Gets all.
func getAll() -> [Person]{
return get(withPredicate: NSPredicate(value:true))
}
// Gets all that fulfill the specified predicate.
// Predicates examples:
// - NSPredicate(format: "name == %@", "Juan Carlos")
// - NSPredicate(format: "name contains %@", "Juan")
func get(withPredicate queryPredicate: NSPredicate) -> [Person]{
let fetchRequest = NSFetchRequest(entityName: Person.entityName)
fetchRequest.predicate = queryPredicate
do {
let response = try context.executeFetchRequest(fetchRequest)
return response as! [Person]
} catch let error as NSError {
// failure
print(error)
return [Person]()
}
}
// Updates a person
func update(updatedPerson: Person){
if let person = getById(updatedPerson.objectID){
person.name = updatedPerson.name
person.age = updatedPerson.age
}
}
// Deletes a person
func delete(id: NSManagedObjectID){
if let personToDelete = getById(id){
context.deleteObject(personToDelete)
}
}
// Saves all changes
func saveChanges(){
do{
try context.save()
} catch let error as NSError {
// failure
print(error)
}
}
}
@GabeCabrera
Copy link

GabeCabrera commented May 25, 2016

I've been experimenting with your code, its good, however I've run into an issue with your read by ID, as firstPerson
let firstPerson = personService.getObjectById(Person[0].objectID!),

any time i use this, it throws an Error saying "Type 'Person.Type' has no subscript members"

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment