Your Data Storage Troubleshooter πŸ› 

Overview

StorageKit

Your Data Storage Troubleshooter πŸ› 


Introduction

StorageKit is a framework which reduces the complexity of managing a persistent layer. You can easily manage your favorite persistent frameworks (Core Data / Realm at the moment), accessing them through a high-level interface.

Our mission is keeping the persistence layer isolated as much as possible from the client codebase. In this way, you can just focus on developing your app. Moreover, you can migrate to another persistent framework easily, keeping the same interface: StorageKit will do almost everything for you.

  • Hassle free setup πŸ‘
  • Easy to use πŸ€–
  • Extensible πŸš€
  • Support for background queries πŸ™ŒπŸΌ
  • Fully tested ( well, almost, ... ☺️ )

StorageKit is a Swift 3 and XCode 8 compatible project.

Build Status

Branch Status
Master BuddyBuild
Develop BuddyBuild

Table of Contents

  1. How it works
  2. Define entities
  3. CRUD
  4. Background operations
  5. Installation
  6. Core Mantainers
  7. Known issues
  8. TODO
  9. License
  10. Credits

How it works

The first step is to create a new Storage object with a specific type (either .CoreData or .Realm) which is the entry-point object to setup StorageKit:

let storage = StorageKit.addStorage(type: .Realm)

or

let storage = StorageKit.addStorage(type: .CoreData(dataModelName: "Example")

The storage exposes a context which is the object you will use to perform the common CRUD operations, for instance:

try storage.mainContext?.fetch(predicate: NSPredicate(format: "done == false"), sortDescriptors: [sortDescriptors], completion: { (fetchedTasks: [RTodoTask]?) in
    self.tasks = fetchedTasks
        // do whatever you want
    }
)

or

let task = functionThatRetrieveASpecificTaskFromDatabase()

do {
    try storage.mainContext?.delete(task)
} catch {
    // manage the error
}

That's it! πŸŽ‰

In just few lines of code you are able to use your favorite database (through the Storage) and perform any CRUD operations through the StorageContext.

Define Entities

Both Core Data and Realm relies on two base objects to define the entities:

Code Data Entity

import RealmSwift

class RTodoTask: Object {
    dynamic var name = ""
    dynamic var done = false
    
    override static func primaryKey() -> String? {
        return "taskID"
    }
}

StorageKit is not able to define your entity class. It means that you must define all your entities manually. It's the only thing you have to do by yourself, please bear with us.

You can create a new entity using in this way:

do {
    try let entity: MyEntity = context.create()
} catch {}

If you are using Realm, entity is an unmanaged object and it should be explicitily added to the database with:

do {
    try storage.mainContext?.add(entity)
} catch {}

CRUD

C as Create

do {
    try let entity: MyEntity = context.create()
} catch {}

This method creates a new entity object: an NSManagedObject for Core Data and an Object for Realm.

Note

You must create a class entity by yourself before using StorageKit. Therefore, for Core Data you must add an entity in the data model, for Realm you must create a new class which extends the base class Object. If you are using the Realm configuration, you have to add it in the storage before performing any update operations.

do {
    try let entity: MyEntity = context.create()
    entity.myProperty = "Hello"

    try context.add(entity)
} catch {}

R as Read

    try context.fetch { (result: [MyEntity]?) in
        // do whatever you want with `result`
    }

As you can see, in order to perform a query over a specific data type, you have to explicitily write it in this way result: [MyEntity]?.

U as Update

do {
    try context.update {
        entity.myProperty = "Hello"
        entity2.myProperty = "Hello 2"
    }
} catch {}

Note

If you are using the Realm configuration, you have to add the entity in the storage (with the method add) before performing any update operations.

D as Delete

do {
    try let entity: MyEntity = context.create()
    entity.myProperty = "Hello"

    try context.delete(entity)
} catch {}

Background Operations

Good news for you! StorageKit has been implemented with a strong focus on background operations and concurrency to improve the user experience of your applications and making your life easier πŸŽ‰

Storage exposes the following method:

storage.performBackgroundTask {[weak self] backgroundContext in
    // the backgroundContext might be nil because of internal errors
    guard let backgroundContext = backgroundContext else { return }
    
    do {
        // perform your background CRUD operations here on the `backgroundContext`
           backgroundContext.fetch { [weak self] (entities: [MyEntity]?) in
        // do something with `entities`
    } catch {
    	print(error.localizedDescription)
    }
}

Now the point is that entities are retrieved in a background context, so if you need to use these entities in another queue (for example in the main one to update the UI), you must pass them to the other context through another method exposed by the Storage:

storage.getThreadSafeEntities(for: context, originalContext: backgroundContext, originalEntities: fetchedTasks, completion: { safeFetchedTaks in
    self?.tasks = safeFetchedTaks
                    
    DispatchQueue.main.async {
        dispatchGroup.leave()
    }
})

The method func getThreadSafeEntities<T: StorageEntityType>(for destinationContext: StorageContext, originalContext: StorageContext, originalEntities: [T], completion: @escaping ([T]) -> Void) create an array of entities with the same data of originalEntities but thread safe, ready to be used in destinatinationContext.

This means that, once getThreadSafeEntities is called, you will be able to use the entities returned by completion: @escaping ([T]) -> Void) in the choosen context.

The common use of this method is:

  1. perform a background operation (for instance a fetch) in performBackgroundTask
  2. move the entities retrieved to the main context using getThreadSafeEntities
storage.performBackgroundTask {[weak self] (backgroundContext, backgroundQueue) in
    guard let backgroundContext = backgroundContext else { return }
    
    do {
        // 1
        backgroundContext.fetch { [weak self] (entities: [MyEntity]?) in
            // 2
            storage.getThreadSafeEntities(for: context, originalContext: backgroundContext, originalEntities: entities, completion: { safeEntities in
                self?.entities = safeEntities
	        })
	    }
    } catch {
    	print(error.localizedDescription)
    }
}

Installation

CocoaPods

Add StorageKit to your Podfile

use_frameworks!
target 'MyTarget' do
    pod 'StorageKit', '~> 0.3.1'
end
$ pod install

Carthage

github "StorageKit/StorageKit" ~> "0.3.1"

Then on your application target Build Phases settings tab, add a "New Run Script Phase". Create a Run Script with the following content:

/usr/local/bin/carthage copy-frameworks

and add the following paths under "Input Files":

$(SRCROOT)/Carthage/Build/iOS/StorageKit.framework

Core Mantainers

Guardians
Ennio Masi @ennioma
Marco Santarossa @MarcoSantaDev

Known Issues

  • Now it's not possible to exclude Realm.framework and RealmSwift.framework from the installation
  • UI Test target doesn't work in the example project

TODO

  • Remove Realm dependency if not needed (the user can decide between Core Data or Realm)
  • Add Reactive interface
  • Distribute through the Swift Package Manager
  • Add more functionalities to the context
  • Add notifications
  • Add migrations

License

StorageKit is available under the MIT license. See the LICENSE file for more info.

Credits:

Boxes icon provided by Nuon Project (LLuisa Iborra). We have changed the boxes color.

Comments
  • Model vs Entity

    Model vs Entity

    Hey,

    I was looking at the examples and it seems like you still have to have 2 fetching codes based on which storage type is it using. The difference is only if is CoreData managed object or Realm object. I think this could also be abstracted out in the way that objects returned from the storage would actually be some structs that the entities would map to. We are using this approach currently at our project.

    Enhancement Discussion 
    opened by zdnk 6
  • 'SortDescriptor' is ambiguous for type lookup in this context

    'SortDescriptor' is ambiguous for type lookup in this context

    What did you do?

    Imported RealmSwift to use Object class and then used also SortDescriptor, everything in the same file.

    β„Ή Please add here the steps to reproduce the issue.

    Platform

    • [x] iOS
    • [x] macOS
    • [x] tvOS

    StorageKit Version

    0.1.1

    What did you expect to happen

    We shouldn't have any compile errors.

    What happened instead?

    The compile error 'SortDescriptor' is ambiguous for type lookup in this context

    Demo Project

    Gist

    Bug Rejected 
    opened by MarcoSantarossa 4
  • Ambiguous fetch

    Ambiguous fetch

    I'd like to write:

    context.fetch { (products: [Product]?) in 
       // things with my products
    }
    
    

    in order to fetch ALL my products. But it doesn't compile. (It says: missing parameter)

    Enhancement Merged 
    opened by sirioz 2
  • Pr 19

    Pr 19

    Goal

    Add the possibility to update an object on add, it it already exists.

    Approach

    the add method implemented in Realm now includes the possibility to update an entity if it already exists with the same identifier

    Open Questions and Pre-Merge TODOs

    • [x] This branch is unit tested
    • [x] This branch is updated with develop
    • [x] The documentation/Readme is up to date with the changes of this branch
    Enhancement Needs Review 
    opened by ennioma 2
  • Errors should be decoupled from the backing storage

    Errors should be decoupled from the backing storage

    Hi,

    I think that error handling should be decoupled from the backing storage. Now if I want to catch errors I need to reintroduce a dependancy to a Realm or CoreData.

    Example:

    do {
                try storage.mainContext?.add(user)
            } catch (let error) // this error depends on the backing storage module
    
    
    Enhancement Merged 
    opened by sirioz 2
  • Wrong method to work with CoreData private context

    Wrong method to work with CoreData private context

    In CoreDataStorage.swift file this function is not well implemented:

    func performBackgroundTask(_ taskClosure: @escaping TaskClosure) {
            let context = makePrivateContext()
    
            backgroundTaskQueue.async { [unowned self] in
                taskClosure(context, self.backgroundTaskQueue)
            }
        }
    

    Instead of a background queue you should use the NSManagedOBjectContest performBlock() method

    Enhancement Merged 
    opened by eugeniobaglieri 2
  • Add supporting for macOS πŸ’»

    Add supporting for macOS πŸ’»

    Goal

    Add supporting for OSX

    Approach

    • Add target macOS
    • Add files to new target
    • Setup project properly

    Open Questions and Pre-Merge TODOs

    • [x] This branch is unit tested
    • [x] This branch is updated with develop
    • [x] The documentation/Readme is up to date with the changes of this branch
    Enhancement Needs Review 
    opened by MarcoSantarossa 1
  • Add error handling

    Add error handling

    Goal

    Add error handling in the public interface

    Approach

    Add errors

    Open Questions and Pre-Merge TODOs

    • [x] This branch is unit tested
    • [x] This branch is updated with develop
    • [x] The documentation/Readme is up to date with the changes of this branch
    Enhancement Needs Review 
    opened by MarcoSantarossa 1
  • Issue 21 - Fetch with default parameters

    Issue 21 - Fetch with default parameters

    Goal

    Add default parameter values for fetch

    Approach

    Add protocol extension with default parameter values.

    Open Questions and Pre-Merge TODOs

    • [x] This branch is unit tested
    • [x] This branch is updated with develop
    • [x] The documentation/Readme is up to date with the changes of this branch
    Enhancement Needs Review 
    opened by MarcoSantarossa 1
  • Cascade deleting

    Cascade deleting

    Goal

    Implemented the very useful (and mandatory) "Cascade deletion" feature. I see no reasons not to use it by default, so I did not expose the "cascading" parameter.

    In Progress 
    opened by sirioz 0
  • Indentation problems + file moved

    Indentation problems + file moved

    Goal

    Using the code in the blog post I've seen multiple issues with indentation. I've also moved a single file in a proper folder

    Approach

    Replace tabs with spaces

    Open Questions and Pre-Merge TODOs

    • [x] This branch is updated with develop
    • [x] The documentation/Readme is up to date with the changes of this branch
    opened by ennioma 0
Releases(0.3.1)
Owner
StorageKit
StorageKit
πŸ›ΆShallows is a generic abstraction layer over lightweight data storage and persistence.

Shallows Shallows is a generic abstraction layer over lightweight data storage and persistence. It provides a Storage<Key, Value> type, instances of w

Oleg Dreyman 620 Dec 3, 2022
Disk is a powerful and simple file management library built with Apple's iOS Data Storage Guidelines in mind

Disk is a powerful and simple file management library built with Apple's iOS Data Storage Guidelines in mind

Saoud Rizwan 3k Jan 3, 2023
StorageManager - FileManager framework that handels Store, fetch, delete and update files in local storage

StorageManager - FileManager framework that handels Store, fetch, delete and update files in local storage. Requirements iOS 8.0+ / macOS 10.10+ / tvOS

Amr Salman 47 Nov 3, 2022
πŸ’Ύ Safe, statically-typed, store-agnostic key-value storage written in Swift!

Storez ?? Safe, statically-typed, store-agnostic key-value storage Highlights Fully Customizable: Customize the persistence store, the KeyType class,

Kitz 67 Aug 7, 2022
An Objective-C wrapper for RocksDB - A Persistent Key-Value Store for Flash and RAM Storage.

ObjectiveRocks ObjectiveRocks is an Objective-C wrapper of Facebook's RocksDB - A Persistent Key-Value Store for Flash and RAM Storage. Current RocksD

Iskandar Abudiab 56 Nov 5, 2022
An efficient, small mobile key-value storage framework developed by WeChat. Works on Android, iOS, macOS, Windows, and POSIX.

δΈ­ζ–‡η‰ˆζœ¬θ―·ε‚ηœ‹θΏ™ι‡Œ MMKV is an efficient, small, easy-to-use mobile key-value storage framework used in the WeChat application. It's currently available on Andr

Tencent 15.4k Jan 6, 2023
pick the voice from the local storage.you can play and pause the voice

flutter_add_voice A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you starte

Mehrab Bozorgi 1 Nov 27, 2021
Easiest local storage library in Swift

SundeedQLite SundeedQLite is the easiest offline database integration, built using Swift language Requirements iOS 12.0+ XCode 10.3+ Swift 5+ Installa

Nour Sandid 15 Sep 23, 2022
An elegant, fast, thread-safe, multipurpose key-value storage, compatible with all Apple platforms.

KeyValueStorage An elegant, fast, thread-safe, multipurpose key-value storage, compatible with all Apple platforms. Supported Platforms iOS macOS watc

null 3 Aug 21, 2022
Typed key-value storage solution to store Codable types in various persistence layers with few lines of code!

?? Stores A typed key-value storage solution to store Codable types in various persistence layers like User Defaults, File System, Core Data, Keychain

Omar Albeik 94 Dec 31, 2022
A GUI for dynamically creating NSPredicates at runtime to query data in your iOS app.

PredicateEditor PredicateEditor is a visual editor for creating and using NSPredicates for querying data in your app. PredicateEditor was inspired by

Arvindh Sukumar 362 Jul 1, 2022
PJAlertView - This library is to make your own custom alert views to match your apps look and feel

PJAlertView - This library is to make your own custom alert views to match your apps look and feel

prajeet 6 Nov 10, 2017
Check your Valorant store from your phone!

Valorant Store Checker Description VSC (Valorant Store Tracker) is an open source iOS app that allows you to track your store and preview your skins.

Gordon 20 Dec 29, 2022
KeyPathKit is a library that provides the standard functions to manipulate data along with a call-syntax that relies on typed keypaths to make the call sites as short and clean as possible.

KeyPathKit Context Swift 4 has introduced a new type called KeyPath, with allows to access the properties of an object with a very nice syntax. For in

Vincent Pradeilles 406 Dec 25, 2022
Realm is a mobile database: a replacement for Core Data & SQLite

Realm is a mobile database that runs directly inside phones, tablets or wearables. This repository holds the source code for the iOS, macOS, tvOS & wa

Realm 15.7k Jan 1, 2023
A library that provides the ability to import/export Realm files from a variety of data container formats.

Realm Converter Realm Converter is an open source software utility framework to make it easier to get data both in and out of Realm. It has been built

Realm 212 Dec 9, 2022
An alternative to Core Data for people who like having direct SQL access.

FCModel 2 An alternative to Core Data for people who like having direct SQL access. By Marco Arment. See the LICENSE file for license info (it's the M

null 1.7k Dec 28, 2022
Synco - Synco uses Firebase's Realtime Database to synchronize data across multiple devices, in real time

Synco Synco uses Firebase's Realtime Database to synchronize a color across mult

Alessio 0 Feb 7, 2022
CoreDataCloudKitShare - Learn how to use Core Data CloudKit

Sharing Core Data Objects Between iCloud Users Implement the flow to share data

null 3 Feb 10, 2022