Skip to content

Instantly share code, notes, and snippets.

@guillianbalisi
Last active December 19, 2018 21:43
Show Gist options
  • Save guillianbalisi/16464513d737e676ff6d06899397b710 to your computer and use it in GitHub Desktop.
Save guillianbalisi/16464513d737e676ff6d06899397b710 to your computer and use it in GitHub Desktop.
Protocol to make fetching model objects from core data easier
import Foundation
import CoreData
protocol CoreDataGettable where Self: NSManagedObject {
static func getSingle(id: String, context: NSManagedObjectContext) -> Self?
static func getList(accId: String, context: NSManagedObjectContext) -> [Self]
static func getSingle(withPredicate predicate: String, args: CVarArg, context: NSManagedObjectContext) -> Self?
}
extension CoreDataGettable {
static func getSingle(id: String, context: NSManagedObjectContext) -> Self? {
let accId = "123"
let request = Self.fetchRequest()
request.predicate = NSPredicate(format: "id == %@ AND accID == %@", id, accId)
let results = try? context.fetch(request)
return results?.first as? Self
}
static func getList(accId: String, context: NSManagedObjectContext) -> [Self] {
let request = Self.fetchRequest()
request.predicate = NSPredicate(format: "accId == %@", accId)
let results = try? context.fetch(request)
return results?.compactMap { $0 as? Self } ?? []
}
static func getSingle(withPredicate predicate: String, args: CVarArg, context: NSManagedObjectContext) -> Self? {
let request = Self.fetchRequest()
request.predicate = NSPredicate(format: predicate, args)
let results = try? context.fetch(request)
return results?.first as? Self
}
}
final class Contact: NSManagedObject { }
extension Contact: CoreDataGettable { }
extension Contact {
static func getActiveContact() -> Contact? {
let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
return getSingle(withPredicate: "id == %@ AND isActive == %@", args: ["123", true], context: context)
}
}
final class BlockedNumber: NSManagedObject { }
extension BlockedNumber: CoreDataGettable { }
let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
let contact = Contact.getSingle(id: "1234", context: context) // contact has type Contact?
let contacts = Contact.getList(accId: "1234", context: context) // contacts has type [Contact]
let specificContact = Contact.getSingle(withPredicate: "id == %@ AND number == %@", args: ["123", "1234567890"], context: context)
let activeContact = Contact.getActiveContact()
let blockedNumber = BlockedNumber.getSingle(id: "1234", context: context) // blockedNumber has type BlockedNumber?
let blockedNumbers = BlockedNumber.getList(accId: "1234", context: context) // blockedNumbers has type [BlockedNumber]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment