Skip to content
/ Pref Public

Pref enables you to easily store Pojo objects in UserDefaults

License

Notifications You must be signed in to change notification settings

pikaboo/Pref

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Pref

CI Status Version License Platform

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Requirements

Installation

Pref is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'Pref'

Pref allows you to store custom objects with ease!

  • Store objects that implement the codable protocol
  • Store arrays that implement the codable protocol

How to use

Create an object that implements the codable protocol:

class DummyCodableObject: NSObject, Codable {

    var name:String!
    var lastName:String!

    enum CodingKeys: String, CodingKey {
        case name
        case lastName = "last_name"
    }
}

Create a Pref variable that accepts your object:

self.myStoredPref = Pref<DummyCodableObject>(prefs:UserDefaults.standard,key:"StamObject")

If you need a defaultValue:

self.myStoredPref = Pref<DummyCodableObject>(prefs:UserDefaults.standard,key:"StamObject", defaultValue:DummyCodableObject())

Use it at will:

let myStoredValue: DummyCodableObject = self.myStoredPref.get()

Or store a new value:

let newDummyCodableObject = DummyCodableObject()
newDummyCodableObject.name = "Lena"
newDummyCodableObject.lastName = "Bru"
self.myStoredPref.set(newDummyCodableObject)

Get notified when the object changes:

NotificationCenter.default.addObserver(forName: self.myStoredPref.willSetNotificationName, object: nil, queue: OperationQueue.main) { (note) in
    let oldValue = note.userInfo?["previousValue"]
    let newValue = note.userInfo?["newValue"]
    //...
}
NotificationCenter.default.addObserver(forName: self.myStoredPref.didSetNotificationName, object: nil, queue: OperationQueue.main) { (note) in
    let newValue = note.userInfo?["newValue"]
    //...
}

You can even store collections:

let myCollectionStoredPref = Pref<[DummyCodableObject]>(prefs:UserDefaults.standard,key:"StamObjectArray")
let newDummyCodableObject = DummyCodableObject()
newDummyCodableObject.name = "Lena"
newDummyCodableObject.lastName = "Bru"
myCollectionStoredPref.set([newDummyCodableObject])

Author

pikaboo

License

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

About

Pref enables you to easily store Pojo objects in UserDefaults

Resources

License

Stars

Watchers

Forks

Packages

No packages published