Nico Gutraich Nico Gutraich - 4 months ago 16
Swift Question

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!

Answer

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