To run the example project, clone the repo, and run pod install
from the Example directory first.
- iOS 8.0+
- macOS 10.10+
- Swift 3.0+
CoreDuck is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'CoreDuck'
import CoreDuck
// Init CoreDuck
let _ = CoreDuck.quack
If you want to see errors in console during development:
CoreDuck.printErrors = true
If you want to specifi name of CoreData *.xcdatamodeld file ("CoreData" by default):
/// Name of your *.xcdatamodel file
CoreDuck.coreDataModelName = "YourModelName"
/// Main NSManagedObjectContext of the app.
/// Primary usage is UIKit, works on the main thread of the app.
/// It's a singleton - always returns the same instance.
let context = NSManagedObjectContext.main
/// Background NSManagedObjectContext.
/// Returns new instance of NSManagedObjectContext each time you access this variable.
/// Use it for persisting changes to CoreData.
let backgroundContext = NSManagedObjectContext.background
Asynchronously:
NSManagedObjectContext.saveWithBlock({ context in
// your code goes here
}, completion: { success in
// completion block
})
Synchronously:
NSManagedObjectContext.saveWithBlockAndWait({ context in
// your code goes here
}, completion: { success in
// completion block
})
To create a new Core Data object in specified context:
if let newEntity = context.new(Entity.self) {
// your code goes here
}
Get reference to NSManagedObject instance in context:
if let entityInContext = context.get(entity) {
// your code goes here
}
Entity.deleteAllObjects()
As an example, let's assume that you have an entity named Person. You can retrieve all Person entities from your persistent store using the following function:
let people = context.findAll(entity: Person.self)
To return the same entities sorted by a specific attribute:
let people = context.findAll(entity: Person.self, sortedBy: "name", ascending: true)
If you want to find object in Core Data by attribute, you can use following functions:
let people = context.findFirst(entity: Person.self, by: "name", with: "John")
let people = context.findFirst(entity: Person.self, by: "officeID", with: 7)
If you want to execute more accurate search request, you can use predicates:
let people = context.findAll(entity: Person.self, with: NSPredicate(format: "entityID IN %@", peopleIDs))
let people = context.fetchAll(entity: Person.self, sortedBy: "entityID", ascending: true, delegate: self)
let people = context.fetchAll(entity: Person.self, with: predicate, sortedBy: "entityID", ascending: true, delegate: self)
let people = context.fetchAll(entity: Person.self, by: "officeID", with: 7, sortedBy: "entityID", ascending: true, delegate: self)
- Maksym Skliarov https://github.com/skliarov
- Yura Voevodin https://github.com/yura-voevodin
CoreDuck is available under the MIT license. See the LICENSE file for more info.