Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

ios - CoreData Swift: How to save and load data?

I'm writing an iOS game in Swift, and I wanted to include a highscore label at the end. I think that the saving function is correct, but the load one is the one which is giving me problems. I already created an entity ("BestScores") and the attributes ("classicBestScoreTF"):

To save the highscore:

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)"
    }    
}

It's not working :( Please help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Saving data:

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()
}

Loading data:

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)!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...