我正在尝试从核心数据中获取分数(NSDates)并返回日期。如果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
我收到错误'致命错误:在展开Optional值时意外发现nil'。
任何帮助将不胜感激:)
答案 0 :(得分:0)
看起来时间是零。
尝试if let hs = time as? NSDate{ highscore = hs}