微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

CoreData Swift:如何保存和加载数据?

如何解决CoreData Swift:如何保存和加载数据?

保存数据:

var person = NSEntityDescription.insertNewObjectForEntityForName("Person", 
inManagedobjectContext: self.managedobjectContext!) as Person
person.name = "Mary"
person.age = Float(arc4random() % 100)

var error : NSError? = nil
if !self.managedobjectContext!.save(&error) {
    NSLog("Unresolved error \(error), \(error!.userInfo)")
    abort()
}

加载数据中:

var error: NSError? = nil
var fReq: NSFetchRequest = NSFetchRequest(entityName: "Frases")    
fReq.predicate = nspredicate(format: "id contains[c] %@", String(day))
var sorter: NSSortDescriptor = NSSortDescriptor(key: "id" , ascending: false)
fReq.sortDescriptors = [sorter]
fReq.returnsObjectsAsFaults = false
let result : [AnyObject] = self.managedobjectContext!.executeFetchRequest(fReq, error:&error)!

解决方法

我正在用Swift编写iOS游戏,但我想在结尾加上高分标签。我认为保存功能是正确的,但负载之一就是给我带来麻烦的功能。我已经创建了一个实体(“
BestScores”)和属性(“ classicBestScoreTF”):

要保存最高分:

var bestscore25 = 1000
var score: int

func savescore() {    
    var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var context:NSManagedObjectContext = appDel.managedObjectContext!
    var score25: AnyObject! = NSEntityDescription.insertNewObjectForEntityForName("BestScores",inManagedObjectContext: context) as NSManagedObject
    score25.setValue(score,forKey: "classicBestScoreTF")
    context.save(nil)
}

func loadscore() {
    var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var context:NSManagedObjectContext = appDel.managedObjectContext!
    bestScore25 = valueForKey("classicBestScoreTF") as Int
}

func endgame() {

    if score > bestScore25 {
        savescore()
        loadscore()
        bestScoreLabel.text = "Best Score: \(bestScore25)"
    }

    if score < bestscore {            
        loadscore()
        bestScoreLabel.text = "Best Score: \(bestScore25)"
    }    
}

它不起作用:(请帮忙!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。