logo
down
shadow

How to save custom color to UserDefaults


How to save custom color to UserDefaults

By : Pranav Vishnu
Date : October 16 2020, 11:12 AM
With these it helps The problem here is that UIColor is not "key-coding" compliant (I am not sure about the correct term), you should have an error like this:
code :


Share : facebook icon twitter icon
How to save a generic custom object to UserDefaults?

How to save a generic custom object to UserDefaults?


By : Jack
Date : March 29 2020, 07:55 AM
it fixes the issue If you want to make the generic class adopt NSCoding and the generic type T is going to be encoded and decoded then T must be one of the property list compliant types.
Property list compliant types are NSString, NSNumber, NSDate and NSData
code :
public protocol PropertyListable {
    associatedtype PropertyListType
    var propertyListRepresentation : PropertyListType { get }
    init(propertyList : PropertyListType)
}
extension String : PropertyListable {
    public typealias PropertyListType = String
    public var propertyListRepresentation : PropertyListType { return self }
    public init(propertyList: PropertyListType) { self.init(stringLiteral: propertyList) }
}

extension Int : PropertyListable {
    public typealias PropertyListType = Int
    public var propertyListRepresentation : PropertyListType { return self }
    public init(propertyList: PropertyListType) { self.init(propertyList) }
}
enum Foo : Int, PropertyListable {
    public typealias PropertyListType = Int

    case north, east, south, west

    public var propertyListRepresentation : PropertyListType { return self.rawValue }
    public init(propertyList: PropertyListType) {
        self.init(rawValue:  propertyList)!
    }
}
open class SMState<T: PropertyListable>: NSObject, NSCoding {
    open var value: T

    open var didEnter: ( (_ state: SMState<T>) -> Void)?
    open var didExit:  ( (_ state: SMState<T>) -> Void)?

    public init(_ value: T) {
        self.value = value
    }

    convenience required public init(coder decoder: NSCoder) {
        let value = decoder.decodeObject(forKey: "value") as! T.PropertyListType
        self.init(T(propertyList: value))
    }

    public func encode(with aCoder: NSCoder) {
        aCoder.encode(value.propertyListRepresentation, forKey: "value")
    }
}
let currentState = SMState<Foo>(Foo.north)
let stateEncodeData = NSKeyedArchiver.archivedData(withRootObject: currentState)
let restoredState = NSKeyedUnarchiver.unarchiveObject(with: stateEncodeData) as! SMState<Foo>
print(restoredState.value)
Save Dictionary of custom objects in Swift using UserDefaults

Save Dictionary of custom objects in Swift using UserDefaults


By : user7643805
Date : March 29 2020, 07:55 AM
With these it helps You need to make your class NSCoding compliant and inherit from NSObject. Change your Contact declaration to class Contact: NSObject, NSCoding {. And Btw conditionally cast to force unwrap it later is pointless. decoder.decodeObject(forKey: "name") as! String
code :
class Contact: NSObject, NSCoding {
    var name = String()
    var phone = String()
    init(name: String, phone: String){
        self.name=name
        self.phone=phone
    }
    required init(coder decoder: NSCoder){
        self.name = decoder.decodeObject(forKey: "name") as! String
        self.phone = decoder.decodeObject(forKey: "phone") as! String
    }
    func encode(with coder: NSCoder){
        coder.encode(name, forKey: "name")
        coder.encode(phone, forKey: "phone")
    }
}
let contactDictionary = ["A":[Contact(name: "Annabel",phone: "000")]]

let encodedData = NSKeyedArchiver.archivedData(withRootObject: contactDictionary)
UserDefaults.standard.set(encodedData, forKey: "contactDictionary")

if let data = UserDefaults.standard.data(forKey: "contactDictionary") {
    print("yep")
    let contactDictionary2 = NSKeyedUnarchiver.unarchiveObject(with: data) as! [String : [Contact]]
}
else{
    print("nope")
}
NSInvalidArgumentException on save an array of custom objects in UserDefaults

NSInvalidArgumentException on save an array of custom objects in UserDefaults


By : Hal
Date : March 29 2020, 07:55 AM
hop of those help? Try Objective-C objects (NSArray, NSDictionary).
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/UserDefaults/AccessingPreferenceValues/AccessingPreferenceValues.html#//apple_ref/doc/uid/10000059i-CH3-97383 .
code :
struct Action { var timestamp: TimeInterval; var winner: String }

var actions: [Action] = []

...
actions.map({ ["time": $0.timestamp, "winner": $0.winner ] as NSDictionary })
// You could also convert the actions manually one by one into NSDictionary
// and append them to an [NSDictionary]



UserDefaults.standard.set(actions as NSArray, forKey: "currentMatch")
UserDefaults.standard.synchronize()
How to use UserDefaults.standard save custom Data?

How to use UserDefaults.standard save custom Data?


By : YosH
Date : March 29 2020, 07:55 AM
To fix the issue you can do If you're using NSKeyedArchiver and NSKeyedUnarchiver, then the objects you archive must subclass NSObject and conform to NSCoding.
You'd have to do something like this:
code :
class People: NSObject, NSCoding {

    let peopleImage : String
    let peopleTime : Int
    let peopleName : String

    init(image:String, second:Int, name:String) {
        peopleImage = image
        peopleTime = second
        peopleName = name
        super.init()
    }

    required init?(coder aDecoder: NSCoder) {
        self.peopleImage = aDecoder.decodeObject(forKey: "peopleImage") as! String
        self.peopleTime = aDecoder.decodeInteger(forKey: "peopleTime")
        self.peopleName = aDecoder.decodeObject(forKey: "peopleName") as! String
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.peopleImage, forKey: "peopleImage")
        aCoder.encode(self.peopleTime, forKey: "peopleTime")
        aCoder.encode(self.peopleName, forKey: "peopleName")
    }
}

class CustomPeopleList: NSObject, NSCoding {

    var peopleList = [
        People(image: "Man", second: 12, name: "Andy"),
        People(image: "Woman", second: 60, name: "Kevin"),
    ]

    override init() {
        super.init()
    }

    required init?(coder aDecoder: NSCoder) {
        self.peopleList = aDecoder.decodeObject(forKey: "peopleList") as! [People]
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.peopleList, forKey: "peopleList")
    }

}

var allPeopleList = CustomPeopleList()

let data = NSKeyedArchiver.archivedData(withRootObject: allPeopleList)
class People: Codable {

    let peopleImage : String
    let peopleTime : Int
    let peopleName : String

    init(image:String, second:Int, name:String) {
        peopleImage = image
        peopleTime = second
        peopleName = name
    }
}

class CustomPeopleList: Codable {

    var peopleList = [
        People(image: "Man", second: 12, name: "Andy"),
        People(image: "Woman", second: 60, name: "Kevin"),
    ]

}

var allPeopleList = CustomPeopleList()

// Can save in whatever format you want. JSON is always light and simple.
let data = try JSONEncoder().encode(allPeopleList)

// Decode the data object later.
let decodedPeopleList = try JSONDecoder().decode(CustomPeopleList.self, from: data)
Saving custom background color with userDefaults

Saving custom background color with userDefaults


By : santosh.thorat
Date : March 29 2020, 07:55 AM
Hope that helps I don't see the other buttons and where you change the background color but let's assume you are using an HeX represantation of a color ypu could save the background color in shared preferences and always use the shared state to set the background.
When you want to save the color to user prefs: UserDefaults.standard.set("#FF2200", forKey: "background_color_hex")
Related Posts Related Posts :
  • Gulp 4 glob to exclude specific files and folders not working
  • Cucumber - how to get scenario tag that is currently being executed
  • Scale PostScript Image via GhostScript
  • How do I stop Object Storage Service file links from expiring?
  • Can I narrow the SPF ranges used by Outlook under Office365?
  • In DBeaver, how can I run an SQL union query from two different connections..?
  • Office.js add-in display dialog dynamic size
  • Drupal Services Plugin ignoring multi-value fields
  • Install gstreamer using cerbero
  • Clojure locking on string value
  • The depth buffer is ignored depending the X/Y position using an orthographic projection
  • FileNet Content Engine query comparing numbers defined as string
  • Mount multiple drives in google colab
  • Coldfusion insert a href URL link into DB Oracle
  • Change Powerlevel9k segment based on current folder
  • weight update of one random layer in multilayer neural network using backpagation?
  • Find most recent date in a list of objects on LocalDate property using Java 8 stream
  • deflateSetDictionary usage
  • Getting Me using Azure OAuth 2 Token
  • How do I get an Aspara Video playauth?
  • Avoiding memory leaks with Commanded in an aggregate that doesn't produce an event
  • Terraform: How to get a boolean from interpolation?
  • How can I disable shift (or any modifier) for some keys but not for others?
  • How to access component model from outside
  • Formatting decimal output when multiplying all numerical values in a string?
  • How to solve the numerical instability to a solution of a system of ordinary differential equations
  • How can I determine if a row has changed?
  • Inherited software that's built on Visual FoxPro, How can I access the source files and edit the program as needed?
  • Problem accessing orion-psb-image-R5.4 on FIWARE Lab using ssh
  • Check if List of Matrix Indexes are adjacent
  • View availability message on summary page Cart
  • Spring AMQP RabbitMQ RPC - Queue with with some messages that do not expect a response
  • App Pool Login Failed Message in New Acumatica Version
  • New-AzureRmSqlDatabaseImport does not accept a DatabaseMaxSizeBytes greater than 5GB
  • How to get the list of queues from a server?
  • Maxima plot discrete data with 3 columns
  • Referencing field from input in a Logstash filter
  • Chapel : Understanding lifetime of managed classes with zip and user-defined iterators
  • Compile With Static Library Using GNAT
  • Is there a way to receive most messages out of the standard SQS Queue? [NOT FIFO]
  • Remove shadow from XFCE panel
  • How do I serialize TransactionBuilder
  • How to disable Rule: one-line in TSLint
  • Automatically Ignore @OneToMany, @ManyToOne
  • Accidently renamed libc.so.6 and cannot chroot within rescue mode
  • A proper way to serialize/deserialize Xodus-dnq entity
  • How to hide the overlays in A frame?
  • PRelue is not supperted with mmdnn?
  • JasperReports: How to pass parameter to subReport
  • Is there built-in web analytics tool in Liferay?
  • 'if' scenario in an equation. How do I implement it?
  • Uncaught [CKEDITOR.editor] The instance "html" already exists
  • Trimming variable in CLLE
  • Slot not being passed from action to layout in Symfony 1.4
  • Are there any disadvantages of using C# 3.0 features?
  • How to download paypal transactions using some API
  • Microsoft CRM could not log you on to the system. Make sure your user record
  • Good acceleration structure for ray sphere tests with spheres that move
  • Draw formatted rich text
  • How can I sum values in column based on the value in another column?
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org