作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在用 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)"
}
}
它不工作 :( 请帮助!
最佳答案
保存数据:
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)!
关于ios - 核心数据 swift : How to save and load data?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25586593/
我是一名优秀的程序员,十分优秀!