Last active
May 21, 2016 05:07
-
-
Save Miguelme/d7d7cd5437533f062dea279dbdbacf7e 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
extension NSManagedObject{ | |
static func createItem(moc: NSManagedObjectContext, entityName: String) -> NSManagedObject { | |
return NSEntityDescription.insertNewObjectForEntityForName( entityName, inManagedObjectContext: moc) | |
} | |
static func getListOfItems(moc: NSManagedObjectContext, entityName: String) -> [NSManagedObject]? { | |
let fetchRequest = NSFetchRequest(entityName: entityName) | |
do { | |
let results = try moc.executeFetchRequest(fetchRequest) | |
return results as? [NSManagedObject] | |
} catch let error as NSError { | |
print("Could not fetch \(error), \(error.userInfo)") | |
return nil | |
} | |
} | |
static func getItemsWhere(moc: NSManagedObjectContext, entityName: String, fieldsAndValues: [(String, String)]) -> [NSManagedObject]? { | |
let fetchRequest = NSFetchRequest(entityName: entityName) | |
let predicates = fieldsAndValues.map { (fieldAndValue:(String, String))-> NSPredicate in | |
return NSPredicate(format:"\(fieldAndValue.0)==%@", fieldAndValue.1) | |
} | |
fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates) | |
do { | |
let results = try moc.executeFetchRequest(fetchRequest) | |
return results as? [NSManagedObject] | |
} catch let error as NSError { | |
print("Could not fetch \(error), \(error.userInfo)") | |
return nil | |
} | |
} | |
static func getItem(moc: NSManagedObjectContext, entityName: String, keyField: String, value: String) -> NSManagedObject? { | |
let fetchRequest = NSFetchRequest(entityName: entityName) | |
fetchRequest.predicate = NSPredicate(format:"\(keyField)==%@", value) | |
do { | |
let results = try moc.executeFetchRequest(fetchRequest) | |
if results.count == 0 { | |
print("There are no item with this value") | |
} else if results.count > 1 { | |
print("There is more than one item with this value") | |
} else { | |
return results[0] as? NSManagedObject | |
} | |
return nil | |
} catch let error as NSError { | |
print("Could not fetch \(error), \(error.userInfo)") | |
return nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment