55

什么是最简单的方法来保存一个然后把它取出来UIColorNSUserDefaults

4

8 回答 8

134

一种方法可能是归档它(就像使用 NSColor,虽然我还没有测试过):

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

并将其取回:

NSData *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:@"myColor"];
UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];
于 2009-08-14T02:42:00.810 回答
74

有了接受的答案,你很快就会在你的代码中得到很多 NSKeyed 归档和取消归档。更简洁的解决方案是扩展 UserDefaults。这正是扩展的用途;UserDefaults 可能不知道 UIColor,因为 UIKit 和 Foundation 是不同的框架。

迅速

extension UserDefaults {

    func color(forKey key: String) -> UIColor? {
        var color: UIColor?
        if let colorData = data(forKey: key) {
            color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor
        }
        return color
    }

    func set(_ value: UIColor?, forKey key: String) {
        var colorData: Data?
        if let color = value {
            colorData = NSKeyedArchiver.archivedData(withRootObject: color)
        }
        set(colorData, forKey: key)
    }

}

斯威夫特 4.2

extension UserDefaults {

    func color(forKey key: String) -> UIColor? {

        guard let colorData = data(forKey: key) else { return nil }

        do {
            return try NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: colorData)
        } catch let error {
            print("color error \(error.localizedDescription)")
            return nil
        }

    }

    func set(_ value: UIColor?, forKey key: String) {

        guard let color = value else { return }
        do {
            let data = try NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: false)
            set(data, forKey: key)
        } catch let error {
            print("error color key data not saved \(error.localizedDescription)")
        }

    }

}

用法

UserDefaults.standard.set(UIColor.white, forKey: "white")
let whiteColor = UserDefaults.standard.color(forKey: "white")

这也可以在具有类别的 Objective-C 中完成。

我在这里添加了 Swift 文件作为要点。

于 2015-06-01T15:00:46.090 回答
7

我自己有答案

节省

const CGFloat  *components = CGColorGetComponents(pColor.CGColor);
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setFloat:components[0]  forKey:@"cr"];
[prefs setFloat:components[1]  forKey:@"cg"];
[prefs setFloat:components[2]  forKey:@"cb"];
[prefs setFloat:components[3]  forKey:@"ca"];

加载

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
UIColor* tColor = [UIColor colorWithRed:[prefs floatForKey:@"cr"] green:[prefs floatForKey:@"cg"] blue:[prefs floatForKey:@"cb"] alpha:[prefs floatForKey:@"ca"]];
于 2009-08-14T02:52:43.543 回答
5

感谢Erica 的 UIColor 类别。我真的不喜欢在首选项中保存 4 个浮点数,只想要一个条目。

因此,使用 Erica 的UIColor类别,我能够将RGB颜色转换为NSString可以保存在首选项中的颜色。

// Save a color
NSString *theColorStr = [self.artistColor stringFromColor];
[[NSUserDefaults standardUserDefaults] setObject:theColorStr forKey:@"myColor"];

// Read a color
NSString *theColorStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"myColor"];
if ([theColorStr length] > 0) {
    self.myColor = [UIColor colorWithString:theColorStr];
} else {
    self.myColor = [UIColor colorWithRed:88.0/255.0 green:151.0/255.0 blue:237.0/255.0 alpha:1.0];
}
于 2009-09-26T22:34:35.573 回答
2

我需要UIColor在用户默认值中存储对象数组。如其他答案所述,想法是转换UIColor为数据并保存该数据。我已经扩展了UIColor

extension UIColor {
   func data() -> Data {
      return NSKeyedArchiver.archivedData(withRootObject: self)
   }
   class func color(withData data: Data) -> UIColor? {
      return NSKeyedUnarchiver.unarchiveObject(with: data) as? UIColor
   }
}

用法:

fileprivate var savedColors: [UIColor]? {
    get {
        if let colorDataArray = UserDefaults.standard.array(forKey: Constants.savedColorsKey) as? [Data] {
            return colorDataArray.map { UIColor.color(withData: $0)! }
        }
        return nil
    }
    set {
        if let colorDataArray = newValue?.map({ $0.data() }) {
            UserDefaults.standard.set(colorDataArray, forKey: Constants.savedColorsKey)
        }

    }
}
于 2017-05-02T23:16:16.803 回答
2

斯威夫特 3,UserDefaults扩展

extension UserDefaults {

    internal func color(forKey key: String) -> UIColor? {
        guard let colorData = data(forKey: key) else {
            return nil
        }

        return NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor
    }

    internal func setColor(_ color: UIColor?, forKey key: String) {
        let colorData: Data?
        if let color = color {
            colorData = NSKeyedArchiver.archivedData(withRootObject: color)
        }
        else {
            colorData = nil
        }

        set(colorData, forKey: key)
    }
}

示例使用

let colorKey = "favoriteColor"

UserDefaults.standard.setColor(UIColor.red, forKey: colorKey)
let favoriteColor = UserDefaults.standard.color(forKey: colorKey)

print("favoriteColor is red: '\(favoriteColor == UIColor.red)'")


此答案基于先前的答案。它已针对 Swift 3 进行了更新。

于 2017-06-14T19:01:01.803 回答
1

迅速

private let colorPickerKey = "ColorPickerKey"

var selectedColor: UIColor? {
    get {
        guard let colorData = UserDefaults.standard.object(forKey: colorPickerKey) as? Data,
            let color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor else { return nil }
        return color
    } set {
        guard let newValue = newValue else {
            UserDefaults.standard.removeObject(forKey: colorPickerKey)
            return
        }
        let colorData = NSKeyedArchiver.archivedData(withRootObject: newValue)
        UserDefaults.standard.set(colorData, forKey: colorPickerKey)
    }
}
于 2019-04-14T14:40:48.533 回答
-4

编辑2:我似乎找到了答案。查看 Erica Sadun 关于扩展 UIColor 的文章。

编辑:此代码似乎不适用于 UIColor 对象。不知道为什么...

下面是一些代码来看看:

将对象保存到 NSUserDefaults 中:

 NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
[userDefaults setObject:someColorObject forKey:@"myColor"];

从 NSUserDefaults 读取对象:

NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
UIColor *someColor = (UIColor *)[userDefaults objectForKey:@"myColor"];
于 2009-08-14T02:10:39.973 回答