Store and retrieve Codable objects to various persistence layers, in a couple lines of code!

Overview

Build Status Test Coverage Platforms Cocoapods Carthage compatible Swift Package Manager compatible Swift Xcode MIT

tl;dr

You love Swift's Codable protocol and use it everywhere, who doesn't! Here is an easy and very light way to store and retrieve Codable objects to various persistence layers, in a few lines of code!

Persistence Layers

PersistenceKit offers 3 layers of persistence suitable for most use cases:

1. UserDefaults

  • Stores data using UserDefaults.
  • Suitable for storing a reasonable number of objects.

2. Files

  • Stores data directly to directories in the app's documents directory using FileManager.
  • Suitable for storing large number of objects.

3. Keychain

  • Stores data to OS's keychain using the Security Framework.
  • Suitable for storing sensitive data, like access tokens.

What's new in v1.3

v1.3 brings Swift 5.0 support

Installation

CocoaPods

To integrate PersistenceKit into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'PersistenceKit'
Carthage

To integrate PersistenceKit into your Xcode project using Carthage, specify it in your Cartfile:

github "Teknasyon-Teknoloji/PersistenceKit"
Swift Package Manager

You can use The Swift Package Manager to install PersistenceKit by adding the proper description to your Package.swift file:

import PackageDescription

let package = Package(
  name: "YOUR_PROJECT_NAME",
  targets: [],
  dependencies: [
    .package(url: "https://github.com/Teknasyon-Teknoloji/PersistenceKit.git", from: "0.1")
  ]
)

Note that the Swift Package Manager is still in early design and development, for more information checkout its GitHub Page

Manually

Add the Sources folder to your Xcode project.

Usage

Let's say you have 2 structs; User and Laptop defined as bellow:

struct User: Codable {
	var id: Int
	var firstName: String
	var lastName: String
	var laptop: Laptop?
}
struct Laptop: Codable {
	var model: String
	var name: String
}

1. Conform to the Identifiable protocol and set the idKey property

The Identifiable protocol lets PersistenceKit knows what is the unique id for each object.

struct User: Codable, Identifiable {
	static let idKey = \User.id
	...
}
struct Laptop: Codable, Identifiable {
	static let idKey = \Laptop.model
	...
}

Notice how User uses Int for its id, while Laptop uses String, in fact the id can be any type. PersistenceKit uses Swift keypaths to refer to properties without actually invoking them. Swift rocks 🤘

2 Create Stores

(uniqueIdentifier: "laptops")! // To save a single object to UserDefaults, create UserDefaultsStore: let userStore = SingleUserDefaultsStore(uniqueIdentifier: "user")! // To save objects to the file system, create FilesStore: let usersStore = FilesStore(uniqueIdentifier: "users") let laptopsStore = FilesStore(uniqueIdentifier: "laptops") // To save a single object to the file system, create SingleFilesStore: let userStore = SingleFilesStore(uniqueIdentifier: "user") // To save a single object to the system's keychain, create SingleKeychainStore: let userStore = SingleKeychainStore(uniqueIdentifier: "user") ">
// To save objects to UserDefaults, create UserDefaultsStore:
let usersStore = UserDefaultsStore<User>(uniqueIdentifier: "users")!
let laptopsStore = UserDefaultsStore<Laptop>(uniqueIdentifier: "laptops")!

// To save a single object to UserDefaults, create UserDefaultsStore:
let userStore = SingleUserDefaultsStore<User>(uniqueIdentifier: "user")!

// To save objects to the file system, create FilesStore:
let usersStore = FilesStore<User>(uniqueIdentifier: "users")
let laptopsStore = FilesStore<Laptop>(uniqueIdentifier: "laptops")

// To save a single object to the file system, create SingleFilesStore:
let userStore = SingleFilesStore<User>(uniqueIdentifier: "user")

// To save a single object to the system's keychain, create SingleKeychainStore:
let userStore = SingleKeychainStore<User>(uniqueIdentifier: "user")

3. Voilà, you're all set!

let macbook = Laptop(model: "A1278", name: "MacBook Pro")
let john = User(userId: 1, firstName: "John", lastName: "Appleseed", laptop: macbook)

// Save an object to a store
try! usersStore.save(john)

// Save an array of objects to a store
try! usersStore.save([jane, steve, jessica])

// Get an object from store
let user = store.object(withId: 1)
let laptop = store.object(withId: "A1278")

// Get all objects in a store
let laptops = laptopsStore.allObjects()

// Check if store has an object
print(usersStore.hasObject(withId: 10)) // false

// Iterate over all objects in a store
laptopsStore.forEach { laptop in
	print(laptop.name)
}

// Delete an object from a store
usersStore.delete(withId: 1)

// Delete all objects in a store
laptops.deleteAll()

// Know how many objects are stored in a store
let usersCount = usersStore.objectsCount

Requirements

  • iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 10.0+
  • Swift 4.2+

Thanks

Special thanks to:

Credits

License

PersistenceKit is released under the MIT license. See LICENSE for more information.

You might also like...
A Generic CoreData Manager to accept any type of objects. Fastest way for adding a Database to your project.
A Generic CoreData Manager to accept any type of objects. Fastest way for adding a Database to your project.

QuickDB FileManager + CoreData ❗️ Save and Retrieve any thing in JUST ONE line of code ❗️ Fast usage dataBase to avoid struggling with dataBase comple

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

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

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

macOS App for App Store Connect to Improve Processing Efficiency and Enjoy the Party.
macOS App for App Store Connect to Improve Processing Efficiency and Enjoy the Party.

Apple Party(苹果派) 一、App 介绍 AppleParty 是三七互娱旗下37手游 iOS 团队研发,实现快速操作 App Store Connect 后台的自动化 macOS 工具。 使用和原理介绍:开源一款苹果 macOS 工具 - AppleParty(苹果派) 支持功能 内购买

YapDB is a collection/key/value store with a plugin architecture. It's built atop sqlite, for Swift & objective-c developers.
YapDB is a collection/key/value store with a plugin architecture. It's built atop sqlite, for Swift & objective-c developers.

YapDatabase is a collection/key/value store and so much more. It's built atop sqlite, for Swift & Objective-C developers, targeting macOS, iOS, tvOS &

💾 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,

Key-Value store for Swift backed by LevelDB

SwiftStore Key/Value store for Swift backed by LevelDB. Usage Create instances of store import SwiftStore // Create a store. let store = SwiftStore(s

A Library for iOS developers to check newer version of app from the app store
A Library for iOS developers to check newer version of app from the app store

swift-app-update-checker A very simple solution check new version of your application is available on store or not. Example To run the example project

CloudKit, Apple’s remote data storage service, provides a possibility to store app data using users’ iCloud accounts as a back-end storage service.
CloudKit, Apple’s remote data storage service, provides a possibility to store app data using users’ iCloud accounts as a back-end storage service.

CloudKit, Apple’s remote data storage service, provides a possibility to store app data using users’ iCloud accounts as a back-end storage service. He

Releases(1.4)
CodableCloudKit allows you to easily save and retrieve Codable objects to iCloud Database (CloudKit)

CodableCloudKit CodableCloudKit allows you to easily save and retrieve Codable objects to iCloud Database (CloudKit) Features ℹ️ Add CodableCloudKit f

Laurent Grondin 65 Oct 23, 2022
Why not use UserDefaults to store Codable objects 😉

tl;dr You love Swift's Codable protocol and use it everywhere, who doesn't! Here is an easy and very light way to store and retrieve -reasonable amoun

Omar Albeik 452 Oct 17, 2022
CodableFiles - Save and load Codable objects from DocumentDirectory on iOS Devices.

Welcome to CodableFiles, a simple library that provides an easier way to save, load or delete Codable objects in Documents directory. It’s primarily a

Egzon Pllana 36 Dec 20, 2022
⚙️ A tiny property wrapper for UserDefaults. Only 60 lines of code.

⚙️ A tiny property wrapper for UserDefaults. Only 60 lines of code. import Persistent extension UserDefaults { // Optional property @Per

Mezhevikin Alexey 6 Sep 28, 2022
🛶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
A type-safe, protocol-based, pure Swift database offering effortless persistence of any object

There are many libraries out there that aims to help developers easily create and use SQLite databases. Unfortunately developers still have to get bogged down in simple tasks such as writing table definitions and SQL queries. SwiftyDB automatically handles everything you don't want to spend your time doing.

Øyvind Grimnes 489 Sep 9, 2022
Modern interface to UserDefaults + Codable support

Default Modern interface to UserDefaults + Codable support What is Default? Default is a library that extends what UserDefaults can do by providing ex

Nicholas Maccharoli 475 Dec 20, 2022
AppCodableStorage - Extends `@AppStorage` in SwiftUI to support any Codable object

AppCodableStorage Extends @AppStorage in SwiftUI to support any Codable object.

Andrew Pouliot 19 Nov 25, 2022
MoreCodable expands the possibilities of `Codable`.

MoreCodable MoreCodable expands the possibilities of "Codable". Installation Carthage github "tattn/MoreCodable" CocoaPods pod 'MoreCodable' Feature D

Tatsuya Tanaka 372 Dec 7, 2022
ObjectBox Swift - persisting your Swift objects superfast and simple

ObjectBox Swift ObjectBox is a superfast, light-weight object persistence framework. This Swift API seamlessly persists objects on-device for iOS and

ObjectBox 380 Dec 19, 2022