SugarRecord is a persistence wrapper designed to make working with persistence solutions like CoreData in a much easier way.

Last update: Jul 29, 2022

SugarRecord

Twitter: @carambalabs CocoaPods Compatible Language: Swift Language: Swift Build Status Carthage Compatible

What is SugarRecord?

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.

paypal

Features

  • Swift 3.0 compatible (Xcode 8.0).
  • Protocols based design.
  • For beginners and advanced users
  • Fully customizable. Build your own stack!
  • Friendly syntax (fluent)
  • Away from Singleton patterns! No shared states 🎉
  • Compatible with OSX/iOS/watchOS/tvOS
  • Fully tested (thanks Nimble and Quick)
  • Actively supported

Setup

CocoaPods

  1. Install CocoaPods. You can do it with gem install cocoapods
  2. Edit your Podfile file and add the following line pod 'SugarRecord'
  3. Update your pods with the command pod install
  4. Open the project from the generated workspace (.xcworkspace file).

Note: You can also test the last commits by specifying it directly in the Podfile line

Available specs Choose the right one depending ton the configuration you need for you app.

pod "SugarRecord/CoreData"
pod "SugarRecord/CoreData+iCloud"

Carthage

  1. Install Carthage. You can do it with brew install carthage.
  2. Edit your Cartfile file and add the following line `github "carambalabs/sugarrecord".
  3. Execute carthage update
  4. Add the frameworks to your project as explained on the Carthage repository.

Reference

You can check generated SugarRecord documentation here generated automatically with CocoaDocs

How to use

Creating your Storage

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 = CoreDataStore.named("db")
    let bundle = Bundle(for: self.classForCoder)
    let model = CoreDataObjectModel.merged([bundle])
    let defaultStorage = try! CoreDataDefaultStorage(store: store, model: model)
    return defaultStorage
}
Creating an iCloud Storage

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(for: self.classForCoder)
    let model = CoreDataObjectModel.merged([bundle])
    let icloudConfig = CoreDataiCloudConfig(ubiquitousContentName: "MyDb", ubiquitousContentURL: "Path/", ubiquitousContainerIdentifier: "com.company.MyApp.anothercontainer")
    let icloudStorage = try! CoreDataiCloudStorage(model: model, iCloud: icloudConfig)
    return icloudStorage
}

Contexts

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:

  • MainContext: Use it for main thread operations, for example fetches whose data will be presented in the UI.
  • SaveContext: Use this context for background operations. The context is initialized when the storage instance is created. That context is used for storage operations.
  • MemoryContext: Use this context when you want to do some tests and you don't want your changes to be persisted.

Fetching data

()) let citiesByName: [City] = try! db.fetch(FetchRequest().sorted(with: "name", ascending: true)) let predicate: NSPredicate = NSPredicate(format: "id == %@", "AAAA") let john: User? = try! db.fetch(FetchRequest().filtered(with: predicate)).first ">
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

Remove/Insert/Update operations

Although Contexts 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:

  • Context: You can use it for fetching, inserting, deleting. Whatever you need to do with your data.
  • Save: All the changes you apply to that context are in a memory state unless you call the 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
}
New model

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.

Creating a model

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
}
Delete a model

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! 🎉

RequestObservable

SugarRecord provides a component, RequestObservable that allows observing changes in the DataBase. It uses NSFetchedResultsController under the hood.

Observing

class Presenter {
  var observable: RequestObservable!

  func setup() {
      let request: FetchRequest = 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 only available for CoreData + OSX since MacOS 10.12

Resources

Contributors

glebosushichopfoxlingZevEisenbergkonyu

yuuki1224YTN01gitter-badgersergigraciaadityatrivedi

Adlai-Hollerakshaynhegdegoingreenstartupthekidctotheameron

davidahouseA8-MokeArasthelLuizZakliterator

madeinqckoliskodukemikerafalwojcikthad

chrispixReadmeCriticavielgrdougangrangej

fjbelchidcvzpepibumur

About

This project is funded and maintained by Caramba. We 💛 open source software!

Check out our other open source projects, read our blog or say 👋 on twitter @carambalabs.

Contribute

Contributions are welcome 🤘 We encourage developers like you to help us improve the projects we've shared with the community. Please see the Contributing Guide and the Code of Conduct.

License

The MIT License (MIT)

Copyright (c) 2017 Caramba

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.

GitHub

https://github.com/modo-studio/SugarRecord
Comments
  • 1. The `SugarRecord-iOS [Debug]` target overrides the `EMBEDDED_CONTENT_CONTAINS_SWIFT`

    Hi, awesome this is such a great API. Though I'm getting this error when trying to install the pod I've added: pod 'SugarRecord', :git => 'https://github.com/gitdoapp/sugarrecord.git' to the pod file though the error happens below. I've tried adding $(inherited) to: Header Search Paths Other Linker Flags Preprocessor Macros in Project -> Target -> Build Settings Though still the same error. Thanks in advance if you can help. /********************************************/ [!] The SugarRecord-iOS [Debug] target overrides the EMBEDDED_CONTENT_CONTAINS_SWIFT build setting defined in Pods/Target Support Files/Pods-SugarRecord-iOS/Pods-SugarRecord-iOS.debug.xcconfig'. This can lead to problems with the CocoaPods installation - Use the$(inherited)` flag, or - Remove the build settings from the target.

    Reviewed by Ged2323 at 2015-12-08 20:59
  • 2. unable to install sugarrecord as submodule

    I'm trying to setup my project to use sugarrecord as a submodule but i am unable to get the application to compile.

    I want to use CoreData and RestKit, and I followed your instructions on the wiki, but it keeps saying builds fails (no error) i'm not sure what i'm doing wrong.

    do you have example application that has sugarrecord imported as a submodule?

    Reviewed by eschan at 2014-11-17 03:55
  • 3. How to manually call the save method?

    I found that when i call model.save() or model.endWriting(), they are not save to database. Sometimes , I want to manually call the save method to save data immediately in database. like:

    [MagicalRecord saveUsingCurrentThreadContextWithBlockAndWait:nil];
    
    Reviewed by foxling at 2014-12-31 03:39
  • 4. RestKit Integration Guide

    I would love to be able to integrate with Restkit. there's already a few examples of how to integrate MagicalRecord with RestKit

    see: https://github.com/m1entus/MZFlickrMania/blob/master/FlickrMania/MZAppDelegate.m#L40-L57

    https://github.com/RestKit/RKGist/blob/master/TUTORIAL.md#configuring-restkit--core-data https://github.com/magicalpanda/MagicalRecord/blob/develop/Docs/GettingStarted.md

    also, do you guys think they will work well together?

    Reviewed by yelled3 at 2014-09-23 08:40
  • 5. Single quote the string predicates on the finder and consider other types

    What?

    • Commented here: https://github.com/SugarRecord/SugarRecord/pull/87#issuecomment-67567564 Just how we have implemented the finder if you want to filter using an string you have to single-quote it which is something most of users forget about.
    • We could split the by() method into: by(name: String, stringValue: String) by(name: String, intValue: String)

    Steps

    • [ ] Add methods to the SugarRecordObjectProtocol
    • [ ] Add methods to the Finder
    • [ ] Test SugarRecord objects methods:
      • [ ] Objective-C
      • [ ] Realm
    • [ ] Teste SugarRecordFinder methods: Note: Basically the tests would consist on checking if the predicate has the right format
    Reviewed by pepicrft at 2014-12-19 05:50
  • 6. Extra Argument 'equalTo:' issue

    Why won't this compile:

    if let extId:NSNumber = subJson["id"].number{

    ==> error here: let category: Categorization? = Categorization.by("extID", equalTo: extId).find()?.first as Categorization?

    Reviewed by jimijon at 2014-12-15 16:25
  • 7. Add RestKit sample to example

    What?

    Adds RestKit sample to the example project Resolves part of https://github.com/SugarRecord/SugarRecord/issues/69

    What should be tested?

    • CocoaPods
    • RestKit view controller

    What tasks are remaining?

    • [x] Add CocoaPods to the project
    • [x] Add RestKit view controller
    Reviewed by rdougan at 2014-12-11 16:53
  • 8. iCould support

    Which iOS version for iCloud is supported iOS 7, iOS 8 or both. And is there some specific steps to add iCloud support different from just change the CoreDataStack and enable iCloud?

    Reviewed by aatanosv-appolica at 2014-12-04 15:36
  • 9. RequestObservable with Sectioned Tableview

    Right now I am struggling to see how the RequestObservable properly captures the ability to have sections within a UITableView.

    The problem is within the information passed through the observe closure. When an insertion, deletion, or update occurs, the closure is only provided with the row from the NSIndexPath, which is not sufficient in determining where the modification actually occurred.

    There are some work arounds that can be done for adds and updates, however, for deletes, which only provide the row which was deleted (and not even the object that was deleted), there is no way to know from which section it was deleted.

    As of right now, the only solution I can figure is having to maintain essentially two lists, one which would be a "master" list, which would be used in the delete scenario, to go row -> object. And then a dictionary to be used as the "sectioned" list, where I maintain the actual "state" of the list.

    Reviewed by cody1024d at 2016-06-28 13:50
  • 10. call observer.OnNext(()) so we can use map functions

    This is to allow using map or flatMap with rx operations

    Re-Create pull from separate branch to avoid updating pull request from my dev branch.

    Signed-off-by: John Grange [email protected]

    Reviewed by grangej at 2016-05-06 05:41
  • 11. Fixed for Swift 1.2

    "Forced failable conversion now uses the as! operator."

    "Immutable (let) properties in struct and class initializers have been revised to standardize on a general “lets are singly initialized but never reassigned or mutated” model."

    Reviewed by dcvz at 2015-02-10 23:41
  • 12. Swift 5 and build fixes

    A pull request from a fork by @aporat that does work on Swift 5 and Xcode 11.x.

    Anyone can use it with pod 'SugarRecord', :git => 'https://github.com/aporat/SugarRecord.git'.

    Reviewed by rivera-ernesto at 2019-11-09 13:25
  • 13. how to update an record ?

    What

    Well I want to update an record which is already inserted.

    Context

    I'm saving records in the database. For example I saved data in db at 1:50 PM and now I sync app at 2:50 PM and want to update the same records , but It do Insert of new record. I tried finding the update function but no success

    Reviewed by patriksharma at 2019-10-28 08:51
  • 14. App Crashes when using observable

    What

    Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An instance of NSFetchedResultsController requires a fetch request with sort descriptors'

    Context

    let request : FetchRequest<DataObject> = FetchRequest<DataObject>()
        
                    self.observable = db.observable(request: request)
                    
                    pedometerDataObservable.observe { (changes) in
                        switch changes {
    
                        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", error.localizedDescription)
                        }
                    }
    
    Reviewed by firecrackerz at 2019-05-10 09:46
  • 15. Taking CoreData operations off main thread

    Hello guys!

    What

    According to best practices, it is better to do Coredata related operations in the background, not to cause any possible performance drops, or UI blocks

    I feel like you are doing some database access in the main thread:

    Context

    Class: CoreDataObservable, function:observe, and Class:CoreDataDefaultStorageTests function:spec, both calling fetch which is doing database operations

    Proposal

    Don't you think it would be better to take these operations off the main thread?

    Reviewed by saraseif at 2018-05-30 18:46
  • 16. Can you adapter Swift 4.1

    What

    Describe here your issue, a bug you found, an idea that you had, something that you think can be improved...

    Context

    Provide information that helps with understanding your issue. For example your use case that the project doesn't cover, what you were doing when you found the bug... You can also provide the version of the library that you were using, how you integrated it with your project, the platform version...

    Proposal

    Attach your own proposal (if you have it). We'll discuss in on the issue to find the best one that fits into the library.

    Reviewed by andanyoung at 2018-05-15 12:03
  • 17. iOS Carthage build fails with Swift 4.1

    What

    After updating to Xcode 9.3 (9E145) and Swift 4.1, an iOS project that depends on SugarRecord 3.1.3 fails to build. Carthage reports a compile error in CoreDataObservable.swift:

    <unknown>:0: error: unable to execute command: Segmentation fault: 11
    
    	/usr/bin/xcrun xcodebuild -workspace /Users/goleinik/Workspaces/***/iOS/Carthage/Checkouts/SugarRecord/SugarRecord.xcworkspace -scheme iOSCoreData -configuration Debug -derivedDataPath /Users/goleinik/Workspaces/***/iOS/Carthage/Build/DerivedData/9.3_9E145/SugarRecord/db21b8b2a568193600ce011d682c3bb6031864fc -sdk iphonesimulator -destination platform=iOS\ Simulator,id=7AFE625D-6C2C-4A03-BD51-706FDB1F0A16 -destination-timeout 3 ONLY_ACTIVE_ARCH=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES build (launched in /Users/goleinik/Workspaces/***/iOS/Carthage/Checkouts/SugarRecord)
    

    Context

    Sugar Record Release 3.1.3 Carthage Version: 0.29.0 OSX 10.13.4 Xcode 9.3 (9E145) Swift 4.1 Base SDK iOS 11.3

    Reviewed by glebo at 2018-04-12 22:37
DataKernel is a minimalistic wrapper around CoreData stack to ease persistence operations.

DataKernel What is DataKernel? DataKernel is a minimalistic wrapper around CoreData stack to ease persistence operations. It is heavily inspired by Su

Jun 2, 2022
Feb 13, 2022
JustPersist is the easiest and safest way to do persistence on iOS with Core Data support out of the box.
JustPersist is the easiest and safest way to do persistence on iOS with Core Data support out of the box.

JustPersist JustPersist is the easiest and safest way to do persistence on iOS with Core Data support out of the box. It also allows you to migrate to

Mar 13, 2022
CoreData based Swift ORM
CoreData based Swift ORM

Swift ORM Features Pure swift objects - no more subclasses of NSManagedObject Extensible attribute system - store any type in CoreData storage by impl

Aug 5, 2022
A Swift framework that wraps CoreData, hides context complexity, and helps facilitate best practices.
A Swift framework that wraps CoreData, hides context complexity, and helps facilitate best practices.

Cadmium is a Core Data framework for Swift that enforces best practices and raises exceptions for common Core Data pitfalls exactly where you make the

May 17, 2022
🎯 PredicateKit allows Swift developers to write expressive and type-safe predicates for CoreData using key-paths, comparisons and logical operators, literal values, and functions.
🎯 PredicateKit allows Swift developers to write expressive and type-safe predicates for CoreData using key-paths, comparisons and logical operators, literal values, and functions.

?? PredicateKit PredicateKit is an alternative to NSPredicate allowing you to write expressive and type-safe predicates for CoreData using key-paths,

Aug 6, 2022
App agenda with CoreData

iOS Agenda App with CORE DATA Ejemplo de código para una aplicación de agenda, gestionando el modelo de datos con CoreData. Built using XCode 13.0 (Sw

Oct 19, 2021
Domain Specific Language to safely build predicates and requests to fetch a CoreData store

SafeFetching This library offers a DSL (Domain Specific Language) to safely build predicates and requests to fetch a CoreData store. Also a wrapper ar

May 8, 2022
iOS app built with UIKit and programatic auto-layouts to learn and apply knowledge. Offline storage using CoreData and Caching

PurpleImage Search Pixabay for images and save them offline to share and view To use: Clone the GitHub project, build and run in Xcode. The API is com

May 10, 2022
Simple IOS notes app written programmatically without storyboard using UIKit and CoreData
Simple IOS notes app written programmatically without storyboard using UIKit and CoreData

Notes Simple Notes app. Swift, UIKit, CoreData Description Simple IOS notes app

Aug 8, 2022
A Swift framework that wraps CoreData, hides context complexity, and helps facilitate best practices.
A Swift framework that wraps CoreData, hides context complexity, and helps facilitate best practices.

Cadmium is a Core Data framework for Swift that enforces best practices and raises exceptions for common Core Data pitfalls exactly where you make them.

May 17, 2022
CoreData + UI/Unit Tests + Pure Swift
CoreData + UI/Unit Tests + Pure Swift

What is it? ???? It's a Todo iOS Application with offline support by the use of Core Data which has been developed as a code challenge. It's written p

Jun 1, 2022
A type-safe, fluent Swift library for working with Core Data
A type-safe, fluent Swift library for working with Core Data

Core Data Query Interface (CDQI) is a type-safe, fluent, intuitive library for working with Core Data in Swift. CDQI tremendously reduces the amount o

Jun 27, 2020
Example repo of working with Core Data in a SwiftUI application

CoreData in SwiftUI This repository serves many purpose. But mostly so I can experiment with Core Data in SwiftUI, and also so I can use it show my ap

Jan 30, 2022
A type-safe, fluent Swift library for working with Core Data
A type-safe, fluent Swift library for working with Core Data

Core Data Query Interface (CDQI) is a type-safe, fluent, intuitive library for working with Core Data in Swift. CDQI tremendously reduces the amount o

Jun 27, 2020
A feature-light wrapper around Core Data that simplifies common database operations.
A feature-light wrapper around Core Data that simplifies common database operations.

Introduction Core Data Dandy is a feature-light wrapper around Core Data that simplifies common database operations. Feature summary Initializes and m

May 11, 2022
A small set of utilities to make working with CoreData and Swift a bit easier.

SuperRecord =================== SUPPORTS SWIFT 2.0 from Version >= 1.4 ** SUPPORTS SWIFT 1.2 from Version <= 1.3 Both iOS and WatchOS A Swift CoreData

Jul 19, 2022
Ipraktikum-swift-solutions - The solutions of the easy entrance swift quiz for the IPraktikum

ipraktikum-swift-solutions The solutions of the easy entrance swift quiz for the

Feb 13, 2022
SwiftUI sample app using Clean Architecture. Examples of working with CoreData persistence, networking, dependency injection, unit testing, and more.
SwiftUI sample app using Clean Architecture. Examples of working with CoreData persistence, networking, dependency injection, unit testing, and more.

Articles related to this project Clean Architecture for SwiftUI Programmatic navigation in SwiftUI project Separation of Concerns in Software Design C

Aug 4, 2022
SwiftUI sample app using Clean Architecture. Examples of working with CoreData persistence, networking, dependency injection, unit testing, and more.
SwiftUI sample app using Clean Architecture. Examples of working with CoreData persistence, networking, dependency injection, unit testing, and more.

Articles related to this project Clean Architecture for SwiftUI Programmatic navigation in SwiftUI project Separation of Concerns in Software Design C

Aug 8, 2022