我有一个小问题,关于在NSUserDefaults中保存颜色的主题。在Objective-C中这很容易:
-(NSColor *)colorForKey:(NSString *)key{
NSData *data;
NSColor *color;
data = [[NSUserDefaults standardUserDefaults] objectForKey:key];
color= [NSUnarchiver unarchiveObjectWithData:data];
if( ! [color isKindOfClass:[NSColor class]] ){
color = nil;
}
return color;
}
-(void)setColor:(NSColor *)color forKey:(NSString *)key{
NSData *data = [NSArchiver archivedDataWithRootObject:color];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:key];
}
以上代码在Objective-C中运行良好,但当我尝试在Swift中编写相同的代码时,在从NSUserDefaults读取颜色时出现错误。
func saveColorForKey (color:NSColor , key:NSString ) {
var data:NSData = NSData()
data = NSArchiver.archivedDataWithRootObject(color)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: key)
}
func colorForKey(key:NSString) -> NSColor{
var data: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey(key)
var color: AnyObject? = NSUnarchiver.unarchiveObjectWithData(data? as NSData)
return color as NSColor
}
感谢您,对于我的英语我很抱歉!