TestsTested | ✓ |
LangLanguage | SwiftSwift |
License | MIT |
ReleasedLast Release | Apr 2017 |
SPMSupports SPM | ✗ |
Maintained by Pedro Piñera.
SugarRecord is a persistence wrapper designed to make working with persistence solutions like CoreData in a much easier way. Thanks to SugarRecord you’ll be able to use CoreData with just a few lines of code: Just choose your stack and start playing with your data.
The library is maintained by @carambalabs. You can reach me at [email protected] for help or whatever you need to commend about the library.
We provide extensions for SugarRecord that offer a reactive interface to the library:
You can check generated SugarRecord documentation here generated automatically with CocoaDocs
A storage represents your database. The first step to start using SugarRecord is initializing the storage. SugarRecord provides a default storages, CoreDataDefaultStorage
.
// Initializing CoreDataDefaultStorage
func coreDataStorage() -> CoreDataDefaultStorage {
let store = CoreData.Store.Named("db")
let bundle = Bundle(forClass: self.classForCoder())
let model = CoreData.ObjectModel.merged([bundle])
let defaultStorage = try! CoreDataDefaultStorage(store: store, model: model)
return defaultStorage
}
SugarRecord supports the integration of CoreData with iCloud. It’s very easy to setup since it’s implemented in its own storage that you can use from your app, CoreDataiCloudStorage
:
// Initializes the CoreDataiCloudStorage
func icloudStorage() -> CoreDataiCloudStorage {
let bundle = Bundle(forClass: self.classForCoder())
let model = CoreData.ObjectModel.merged([bundle])
let icloudConfig = CoreDataiCloudConfig(ubiquitousContentName: "MyDb", ubiquitousContentURL: "Path/", ubiquitousContainerIdentifier: "com.company.MyApp.anothercontainer")
return CoreDataiCloudStorage(model: model, iCloud: icloudConfig)
}
Storages offer multiple kind of contexts that are the entry points to the database. For curious developers, in case of CoreData a context is a wrapper around NSManagedObjectContext
. The available contexts are:
let pedros: [Person] = try! db.fetch(FetchRequest<Person>().filtered(with: "name", equalTo: "Pedro"))
let tasks: [Task] = try! db.fetch(FetchRequest<Task>())
let citiesByName: [City] = try! db.fetch(FetchRequest<City>().sorted(with: "name", ascending: true))
let predicate: NSPredicate = NSPredicate(format: "id == %@", "AAAA")
let john: User? = try! db.fetch(FetchRequest<User>().filtered(with: predicate)).first
Although Context
s offer insertion
and deletion
methods that you can use it directly SugarRecords aims at using the operation
method method provided by the storage for operations that imply modifications of the database models:
save()
method. That method will persist the changes to your store and propagate them across all the available contexts.do {
db.operation { (context, save) throws in
// Do your operations here
try save()
}
} catch {
// There was an error in the operation
}
You can use the context new()
method to initialize a model without inserting it in the context:
do {
db.operation { (context, save) throws in
let newTask: Track = try context.new()
newTask.name = "Make CoreData easier!"
try context.insert(newTask)
try save()
}
} catch {
// There was an error in the operation
}
In order to insert the model into the context you use the insert() method.
You can use the create()
for initializing and inserting in the context in the same operation:
do {
db.operation { (context, save) throws -> Void in
let newTask: Track = try! context.create()
newTask.name = "Make CoreData easier!"
save()
}
}
catch {
// There was an error in the operation
}
In a similar way you can use the remove()
method from the context passing the objects you want to remove from the database:
do {
db.operation { (context, save) throws in
let john: User? = try context.request(User.self).filteredWith("id", equalTo: "1234").fetch().first
if let john = john {
try context.remove([john])
try save()
}
}
} catch {
// There was an error in the operation
}
This is the first approach of SugarRecord for the interface. We’ll improve it with the feedback you can report and according to the use of the framework. Do not hesitate to reach us with your proposals. Everything that has to be with making the use of CoreData easier, funnier, and enjoyable is welcome!
🎉
SugarRecord provides a component, RequestObservable
that allows observing changes in the DataBase. It uses NSFetchedResultsController
under the hood.
Observing
class Presenter {
var observable: RequestObservable<Track>!
func setup() {
let request: FetchRequest<Track> = FetchRequest<Track>().filtered(with: "artist", equalTo: "pedro")
self.observable = storage.instance.observable(request)
self.observable.observe { changes in
case .Initial(let objects):
print("\(objects.count) objects in the database")
case .Update(let deletions, let insertions, let modifications):
print("\(deletions.count) deleted | \(insertions.count) inserted | \(modifications.count) modified")
case .Error(let error):
print("Something went wrong")
}
}
}
Retain: RequestObservable must be retained during the observation lifecycle. When the
RequestObservable
instance gets released from memory it stops observing changes from your storage.NOTE: This was renamed from Observable -> RequestObservable so we are no longer stomping on the RxSwift Observable namespace.
RequestObservable
is not available for CoreData + OSX
This project is funded and maintained by Caramba. We
Check out our other open source projects, read our blog or say
Contributions are welcome
The MIT License (MIT)
Copyright © <2014>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.