将UIColor保存到NSUserDefaults并从NSUserDefaults加载

时间:2009-08-14 01:56:42

标签: objective-c cocoa-touch nsuserdefaults uicolor

UIColor保存到NSUserDefaults然后将其恢复的最简单方法是什么?

8 个答案:

答案 0 :(得分:131)

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

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

并将其取回:

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

答案 1 :(得分:59)

使用the accepted answer,您很快就会收到很多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)
    }

}

Swift 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文件添加为要点here

答案 2 :(得分: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"]];

答案 3 :(得分:5)

感谢Erica's UIColor category。我不喜欢在首选项中保存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];
}

答案 4 :(得分:2)

Swift 3,var errorDomain = 'pagedoesnotexist.com'; var filter = { url: [ //{urlPrefix: 'about:neterror'} // works // The simple RegExps in the following urlMatches have the // possibility to produce false positives on matching the // domain. In other words, some other error URLs could match // this RegExp. However, a more complex RegExp which would // prevent such false positive matches would depend on the // exact criteria you desire to use for matching. For // instance, are you wanting to match sub-domains? Only HTTP? // both HTTP and HTTPS? Any protocol (e.g. FTP)? {urlMatches: '^about:neterror\\?.*' + errorDomain + '.*'} // works. //{urlMatches: '.*pagedoesnotexist.com.*'} // works //{urlMatches: '.*page.*'} // works //{queryContains: 'pagedoesnotexist.com'} // Does NOT work (potentially a Firefox bug) //{queryContains: 'page'} // Does NOT work (potentially a Firefox bug) ] } function logOnDOMContentLoaded(details) { console.log("onDOMContentLoaded: " + details.url); } browser.webNavigation.onDOMContentLoaded.addListener(logOnDOMContentLoaded, filter); 扩展名

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)
    }
}


这个答案基于a previous answer。它已针对Swift 3进行了更新。

答案 5 :(得分:1)

我需要在用户默认值中存储NSURL *url = _requestTokenUrl; if (url != nil) { self.requestTokenRequest = [[OAMutableURLRequest alloc] initWithURL:url consumer:_consumer token:nil realm:nil signatureProvider:nil nonce:nil timestamp:nil]; } else { // `_requestTokenUrl` was nil, act accordingly } 个对象的数组。如其他答案所述,Idea是将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
   }
}

答案 6 :(得分:1)

迅速

\n something \n

答案 7 :(得分:-4)

编辑2:我似乎找到了answer。查看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"];