I have a litle problem with saving a color in NSUserDefaults . In objective-c is easy :
-(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];
}
The above code works fine in objective-c, but when i try to write same code in swift, I receive errors at reading color from 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
}
Thanks , and sorry for my english !