我有一個在NSUserDefaults中保存顏色的問題。在Objective-C很簡單:如何在swift中保存NSUserDefaults中的顏色?
-(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,但是當我嘗試寫在迅速相同的代碼,我從讀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
}
謝謝,對不起我的英語!
如果我的回答是真實的,那麼請在地點打勾,以便將來這可以幫助其他人。謝謝 – 2014-10-20 11:23:17