我有以下代码来访问Core Data数据库并检索字符串。 (格式化为xx:xx:xx)
我的目标是遍历时间(String)以找到最大的持续时间。我的代码如下:
func loadHighscore() {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context = appDel.managedObjectContext
var score = NSFetchRequest(entityName: "Scores")
score.returnsObjectsAsFaults = false
var scores : NSArray = context!.executeFetchRequest(score, error: nil)!
println("\(scores.count) scores available")
var highestMins = 0
var highestSecs = 0
var highestFrac = 0
var currentMins : Int
var currentSecs : Int
var currentFrac : Int
if scores.count > 0 {
var time = scores.firstObject!
var myStringArr = time.componentsSeparatedByString(":")
currentMins = myStringArr[0] as! Int
currentSecs = myStringArr[1] as! Int
currentFrac = myStringArr[2] as! Int
if currentMins > highestMins {
highestMins = currentMins
highestSecs = currentSecs
highestFrac = currentFrac
}
else if currentMins == highestMins {
if currentSecs > highestSecs {
highestMins = currentMins
highestSecs = currentSecs
highestFrac = currentFrac
}
else if currentSecs == highestSecs {
if currentFrac > highestFrac {
highestMins = currentMins
highestSecs = currentSecs
highestFrac = currentFrac
}
//accounts for the times being identical
else {
highestMins = currentMins
highestSecs = currentSecs
highestFrac = currentFrac
}
}
}
println("Highscore: \(highestMins):\(highestSecs):\(highestFrac)")
}
else {
println("0 scores returned")
}
}
当我遵守此规则时,我收到了错误
'由于未捕获的异常'NSInvalidArgumentException',原因: ' - [NSManagedObject componentsSeparatedByString:]:无法识别 选择器发送到实例'。
我认为这可能是因为我没有正确地从Core Data数据库中获取/拆分字符串值。
如何正确检索此字符串的任何想法都将非常感激!
答案 0 :(得分:2)
CoreData无法存储字符串。它只存储NSManagedObjects。您执行的获取的结果是NSManagedObjects的列表。 您需要创建一个带有字段的实体来存储时间。
例如,在xcdatamodeld中创建一个名为Score的实体,其字段类型为String,称为time。
然后,在您的代码中,执行以下操作:
(...)
var score = NSFetchRequest(entityName: "Score")
score.returnsObjectsAsFaults = false
var scores : NSArray = context!.executeFetchRequest(score, error: nil)!
println("\(scores.count) scores available")
var highestMins = 0
var highestSecs = 0
var highestFrac = 0
var currentMins : Int
var currentSecs : Int
var currentFrac : Int
for score in scores {
var time = score.valueForKey("time") as! String
var myStringArr = time.componentsSeparatedByString(":")
(...)