Code Monkey home page Code Monkey logo

userdefaultsstore's Introduction

⚠️ Deprecated ⚠️

Please use the new Stores library instead.


Build Status Test Coverage Swift versions Platforms 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 -reasonable amount 😅- of Codable objects, in a couple lines of code!


New in v3.0

  • Both UserDefaultsStore and SingleUserDefaultsStore are thread safe!
  • BREAKING: Use of custom encoder/decoder has been removed.
  • BREAKING: Snapshots have been removed.

Installation

Swift Package Manager

  1. Add the following to your Package.swift file:
dependencies: [
    .package(url: "https://github.com/omaralbeik/UserDefaultsStore.git", from: "3.0.0")
]
  1. Build your project:
$ swift build

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
}

Here is how you store them in UserDefaultsStore:

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

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

struct User: Codable, Identifiable {
    ...
}
struct Laptop: Codable, Identifiable {
    var id: String { model }
    ...
}

2. Create UserDefaults Stores

let usersStore = UserDefaultsStore<User>(uniqueIdentifier: "users")
let laptopsStore = UserDefaultsStore<Laptop>(uniqueIdentifier: "laptops")

3. Voilà, you're all set!

let macbook = Laptop(model: "A1278", name: "MacBook Pro")
let john = User(id: 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

Looking to store a single item only?

Use SingleUserDefaultsStore, it enables storing and retrieving a single value of Int, Double, String, or any Codable type.

Requirements

  • iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 6.0+
  • Swift 5.0+

Thanks

Special thanks to:

Credits

Icon made by freepik from flaticon.com.

License

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

userdefaultsstore's People

Contributors

batarian711 avatar dependabot[bot] avatar omaralbeik avatar terwanerik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

userdefaultsstore's Issues

Logo contribution

I'm sorry sir, my github account was suspended, I will now open it up pr again.

userr

Not working with duplicate object

let cartSaved = UserDefaultsStore<CartItem>(uniqueIdentifier: "cart")

When I add the same product with the same id I want to increment the quantity but the saved cart (::allObject) method return me the same product

  var cart  = getCart()
        
        var targetItem  = cart.first(where: {$0.product.id == cartItem.product.id}) // <-- targetItem is a product in the [CartItem]
                
        
        if targetItem == nil  {
        
            print("prodct added ! ")
            cartItem.quantity += 1
            cart.append(cartItem)
            
            
        }else{
            
            targetItem?.quantity += 1
            
        }
        
        saveCart(cart: cart) // <--- here save again it should save the targetItem += 1

JSON Encoding doesn't store JSON

In inspecting the plist files that are created, I was surprised to see that they're not human readable, even though a JSONEncoder is being used. The issue is that you're taking the encoding and storing that directly, rather than converting it to a string.

I think it would be nice to have that at least as an option, to aid in debugging. To do so, you'd change save to look more like:

	public func save(_ object: T) throws {
		let data = try encoder.encode(object)
                if let str = String(data: json, encoding: .utf8) {
		     store.set(str, forKey: key(for: object))
		     increaseCounter()
                } else {
                     // throw appropriate error.
                }
	}

Doesn't work with classes

After porting a bunch of code to work with UserDefaultsStore, I discovered that the "objects" you store can only be structs. It would be good to document this.

Fix Codecov

The project has a 100% test coverage, however codecov is not working for some reason 😭
If you have an idea how to fix it, your help is highly appriciated

Misleading docs

Based on the documentation in the readme, I got the impression that a laptop owned by a user came from the laptop store. Meaning that what was serialized to the store was the key to the laptop and that when I retrieved a user, it would also retrieve the laptop from the store.

What's actually happening is that the laptop is serialized into the data for the user. So if I were to say that John owned a MacBook and then changed the description of the MacBook in the laptop store, when I retrieved john's record, I would get the updated Macbook data. Instead, I get whatever was serialized when I saved john to the user store.

Does this make sense? I think it would be good to be explicit about what's happening, because I was getting inconsistency errors based on what I thought the docs were implying.

Use hash value as key?

Looks dangerous.

Hash values are not guaranteed to be equal across different executions of your program. Do not save hash values to use during a future execution.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.