转换任何对象?到 NSDate
Converting AnyObject? to NSDate
我正在尝试从核心数据中获取分数 (NSDates) 和 return 日期。如果 coreData 为空则返回 00:00:00.00,否则显示第一个日期。
我有以下代码:
func getHighScore() -> NSDate {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context = appDel.managedObjectContext
var entity = NSFetchRequest(entityName: "Score")
entity.returnsObjectsAsFaults = false
var score = NSFetchRequest(entityName: "Score")
score.returnsObjectsAsFaults = false
let results: [AnyObject]
results = context!.executeFetchRequest(score, error: nil)!
println("\(results.count) scores available")
dateFormatter.dateFormat = "HH:mm:ss.SS"
var highScore : NSDate = dateFormatter.dateFromString("00:00:00.00")!
if (results.count>0){
var time: AnyObject? = results[0].valueForKey("time")
println(time)
var highScore = time as NSDate
return highScore
}
else {
return dateFormatter.dateFromString("00:00:00.00")!
}
}
当我尝试这条线时:
var highScore = time as NSDate
我收到错误“AnyObject?不能转换为 NSDate',当我强制向下转换时它变为:
var highScore = time as! NSDate
我收到错误 'fatal error: unexpectedly found nil while unwrapping an Optional value'。
任何帮助将不胜感激:)
看来时间是零。
尝试if let hs = time as? NSDate{ highscore = hs}
我正在尝试从核心数据中获取分数 (NSDates) 和 return 日期。如果 coreData 为空则返回 00:00:00.00,否则显示第一个日期。
我有以下代码:
func getHighScore() -> NSDate {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context = appDel.managedObjectContext
var entity = NSFetchRequest(entityName: "Score")
entity.returnsObjectsAsFaults = false
var score = NSFetchRequest(entityName: "Score")
score.returnsObjectsAsFaults = false
let results: [AnyObject]
results = context!.executeFetchRequest(score, error: nil)!
println("\(results.count) scores available")
dateFormatter.dateFormat = "HH:mm:ss.SS"
var highScore : NSDate = dateFormatter.dateFromString("00:00:00.00")!
if (results.count>0){
var time: AnyObject? = results[0].valueForKey("time")
println(time)
var highScore = time as NSDate
return highScore
}
else {
return dateFormatter.dateFromString("00:00:00.00")!
}
}
当我尝试这条线时:
var highScore = time as NSDate
我收到错误“AnyObject?不能转换为 NSDate',当我强制向下转换时它变为:
var highScore = time as! NSDate
我收到错误 'fatal error: unexpectedly found nil while unwrapping an Optional value'。
任何帮助将不胜感激:)
看来时间是零。
尝试if let hs = time as? NSDate{ highscore = hs}