DataKernel is a minimalistic wrapper around CoreData stack to ease persistence operations.

Related tags

Core Data DataKernel
Overview

DataKernel

Language: Swift Language: Swift Build Status Carthage compatible CocoaPods compatible

What is DataKernel?

DataKernel is a minimalistic wrapper around CoreData stack to ease persistence operations. It is heavily inspired by SugarRecord but have no external dependencies (except Cocoa of course) and with some refinements. It is covered with unit tests.

If you have any propositions please file issue. If you need usage examples - see unit test, it is very straightforward

Features

  • Swift (tested in XCode 9.1)
  • Protocols based design
  • Fully tested
  • Actively supported
  • Rich set of operations (but I think something may be missed)
  • No iCloud yet (but planned)

Note

  • context.wipe uses NSBatchDeleteRequest on iOS 9 and OSX 10.11, it gives big performance improvements, but can cause problems if you use patterns like wipe all and create new, because it acts directly on persistent store (see Apple WWDC 2015 video or slides)

Setup

CocoaPods

  1. Install CocoaPods. You can do it with gem install cocoapods
  2. Edit your Podfile file and add the following line pod 'DataKernel' (you have to use use_frameworks!, because this is a Swift pod)
  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

Carthage

  1. Install Carthage on your computer using brew install carthage
  2. Edit your Cartfile file adding the following line github "mrdekk/DataKernel"
  3. Update and build frameworks with carthage update
  4. Add generated frameworks to your app main target following the steps here
  5. Link your target with CoreData library (from Build Phases)

How to use

Creating your Storage

A storage is a general wrapper around CoreData PersistentStoreCoordination and PersistentStores. The first step you need to get started is to create CoreDataLocalStorage.

let store = StoreRef.Named("test1")
let bundle = NSBundle(forClass: self.classForCoder)
let model = ModelRef.Merged([bundle])
let storage = try! CoreDataLocalStorage(store: store!, model: model!, migration: true)

Contexts

Storage offer access to uiContext (NSManagedObjectContext on main thread to GET data from storage). All modification operations on CoreData entities should be performed with perform operation on storage.

Fetching data

()) let cars: [Cars] = try! storage.uiContext.fetch(Request().sorted("model", ascending: true)) let predicate = NSPredicate(format: "model == %@", "CRZ") let crz: Car? = try! storage.uiContext.fetch(Request(predicate: predicate)).first ">
let cars: [Cars] = try! storage.uiContext.fetch(Request<Car>().filtered("mark", equalTo: "Honda"))
let cars: [Cars] = try! storage.uiContext.fetch(Request<Car>())
let cars: [Cars] = try! storage.uiContext.fetch(Request<Car>().sorted("model", ascending: true))

let predicate = NSPredicate(format: "model == %@", "CRZ")
let crz: Car? = try! storage.uiContext.fetch(Request<Car>(predicate: predicate)).first

Remove/Insert/Update operations

All modification operations should be performed under perform operation due to it handles all core data context/threading things internally and you can safely use modification operations under them.

save operation perform recursive save with nesting context on core data stack. So, if you change entities that already loaded in uiContext, they will be updated.

Note the first parameter ephemeral on perform function. If it is true, new context for this operation will be created, and then after save succeeded it will be removed. Creation of contexts in CoreData is rather cheap operations, so don't worry. If you don't need to save data in ephemeral context, just don't call save. If you set ephemeral = false then a pre-created special save context will be used for all ephemeral = false operations.

do {
  storage.perform(true) { (context, save) throws -> Void in
    // do you unit of work here
    save()
  }
}
catch {
  // There was an error in the operation
}
Creating a model

You can use the create() for initializing and inserting in the context in the same operation:

do {
  storage.perform(true) { (context, save) throws -> Void in
    let newCar: Car = try! context.create()
    newCar.model = "Honda"
    newCar.mark = "CRZ"
    save()
  }
}
catch {
  // There was an error in the operation
}

Upsert a model

Upsert - update or insert first search the entity in storage, and then if it is not found creates it. Just call the acquire function.

Important: to get this feature work, you should add model property pk and set it to name of the field, that is primary key of this entity. Moreover, this property should be indexed. It is needed to achieve needed level of performance.

do {
  storage.perform(true) { (context, save) throws -> Void in
    let car: Car = try! context.acquire("CRZ")
  }
}
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 {
  storage.perform(true) { (context, save) throws -> Void in
    let car: Car? = try! context.fetch(Request<Car>.filtered("model", equalTo: "CRZ")).first
    if let car = car {
      try! context.remove([car])
      save()
    }
  }
}
catch {
  // There was an error in the operation
}

Contributing

Support

If you want to communicate any issue, suggestion or even make a contribution, you have to keep in mind the flow bellow:

  • If you need help, ask your doubt in Stack Overflow using the tag 'datakernel'
  • If you want to ask something in general, use Stack Overflow too.
  • Open an issue either when you have an error to report or a feature request.
  • If you want to contribute, submit a pull request, and remember the rules to follow related with the code style, testing, ...

Code of conduct

This project adheres to the [Open Code of Conduct][code-of-conduct]. By participating, you are expected to honor this code. [code-of-conduct]: http://todogroup.org/opencodeofconduct/#DataKernel/[email protected]

License

The MIT License (MIT)

Copyright (c) <2017>

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.

You might also like...
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

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

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

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

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

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.

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

Aplikasi iOS To Do List dengan Storyboard & Local CoreData (Database Xcode)
Aplikasi iOS To Do List dengan Storyboard & Local CoreData (Database Xcode)

ToDoList Aplikasi iOS ToDoList adalah sebuah aplikasi CRUD sederhana berbasis iOS yang digunakan untuk membuat sebuah list item. Aplikasi ini dibuat m

A simple application for retrieving lunch menus of selected restaurants around FIT CTU
A simple application for retrieving lunch menus of selected restaurants around FIT CTU

lunch_guy-ios (in progress) A simple application for retrieving lunch menus of selected restaurants using https://github.com/tomaskadlec/lunch_guy API

Comments
  • Bug with chaining Request.filter

    Bug with chaining Request.filter

    Request(...).filter(...).filter 
    

    applies NSPredicate only from last filter, it is a bug. We should

    1. deny chaining .filter.filter
    2. add those chaning options
    Request(...).filter(...).or(...)
    Request(...).filter(...).and(...)
    

    or and and

    bug enhancement 
    opened by mrdekk 1
  • Fix danger behaviour after upgrading to Swift 2.3

    Fix danger behaviour after upgrading to Swift 2.3

    In the enum StoreRef we now have force unwraping optional. We need to fix it, may be involving of optional NSURL? as return value. But it will require some code rewrites in other parts. Now force unwrap may crash the app if programmer call location with wrong url

    dangerous 
    opened by mrdekk 0
Owner
Denis
do the software magic
Denis
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

Fuzz Productions 33 May 11, 2022
Arctanyn 0 Dec 24, 2022
A minimalistic, thread safe, non-boilerplate and super easy to use version of Active Record on Core Data.

Skopelos A minimalistic, thread-safe, non-boilerplate and super easy to use version of Active Record on Core Data. Simply all you need for doing Core

Alberto De Bortoli 235 Sep 9, 2022
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

Just Eat 167 Mar 13, 2022
JSQCoreDataKit - A swifter Core Data stack

JSQCoreDataKit A swifter Core Data stack About This library aims to do the following: Encode Core Data best practices, so you don't have to think "is

Jesse Squires 596 Dec 3, 2022
The Big Nerd Ranch Core Data Stack

BNR Core Data Stack The BNR Core Data Stack is a small Swift framework that makes it both easier and safer to use Core Data. A better fetched results

Big Nerd Ranch 561 Jul 29, 2022
100% Swift Simple Boilerplate Free Core Data Stack. NSPersistentContainer

DATAStack helps you to alleviate the Core Data boilerplate. Now you can go to your AppDelegate remove all the Core Data related code and replace it wi

Nes 216 Jan 3, 2023
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

Prisma Labs 89 Dec 29, 2022
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

Jason Fieldman 123 Oct 18, 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 PredicateKit is an alternative to NSPredicate allowing you to write expressive and type-safe predicates for CoreData using key-paths,

Faiçal Tchirou 352 Jan 3, 2023