How to save a color in NSUserDefaults in swift?

后端 未结 2 1501
无人共我
无人共我 2021-02-09 15:25

I have a litle problem with saving a color in NSUserDefaults . In objective-c is easy :

-(NSColor *)colorForKey:(NSString *)key{
NSData  *data;
NSColor *color;
         


        
相关标签:
2条回答
  • 2021-02-09 16:21

    For Objective C

    place like this.

    NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:color];
    [[NSUserDefaults standardUserDefaults] setObject:colorData forKey:@"myColor"];
    

    To get back like this.

    NSData *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:@"myColor"];
    UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
    

    For Swift

    set like this

     var userSelectedColor : NSData? = (NSUserDefaults.standardUserDefaults().objectForKey("UserSelectedColor") as? NSData)
    
    if (userSelectedColor != nil) {
        var colorToSetAsDefault : UIColor = UIColor.redColor()
        var data : NSData = NSKeyedArchiver.archivedDataWithRootObject(colorToSetAsDefault)
        NSUserDefaults.standardUserDefaults().setObject(data, forKey: "UserSelectedColor")
        NSUserDefaults.standardUserDefaults().synchronize()
        println("SET DEFAULT USER COLOR TO RED")
    }
    

    get like this.

    if let userSelectedColorData = NSUserDefaults.standardUserDefaults().objectForKey("UserSelectedColor") as? NSData {
        if let userSelectedColor = NSKeyedUnarchiver.unarchiveObjectWithData(userSelectedColorData) as? UIColor {
            println(userSelectedColor)
        }
    }
    

    For Swift 4.2

    place like this.

    let colorToSetAsDefault : UIColor = UIColor.red
    let data : Data = NSKeyedArchiver.archivedData(withRootObject: colorToSetAsDefault) as Data
    UserDefaults.standard.set(data, forKey: "UserSelectedColor")
    UserDefaults.standard.synchronize()
    print("SET DEFAULT USER COLOR TO RED")
    

    To get back like this.

    if let userSelectedColorData = UserDefaults.standard.object(forKey: "UserSelectedColor") as? Data {
        if let userSelectedColor = NSKeyedUnarchiver.unarchiveObject(with:userSelectedColorData as Data) as? UIColor {
            print(userSelectedColor)
        }
    }
    
    0 讨论(0)
  • 2021-02-09 16:30

    Storing an NSColor instance in user defaults

    store the value in aColor in user defaults as the value for key aKey

    NSData *theData=[NSArchiver archivedDataWithRootObject:aColor]; [[NSUserDefaults standardUserDefaults] setObject:theData forKey:aKey];

    0 讨论(0)
提交回复
热议问题