Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 330
Nico Gutraich Avatar asked Aug 30 '14 20:08

Nico Gutraich


People also ask

How do I save and fetch data in Core Data Swift?

Let's start with CoreDataOpen Xcode create new iOS project single view application name the application and hit use core data and click next. After clicking next we have a new file named CoreDataDemo. xcedatamodeld, In this file we will create our entity.

How do I save in Core Data?

Right-click on your project's folder in the project navigator and then New File… In the new window, type “data” in the top right corner, select Data Model, and press Next. Give it a name, and save it. Now, let's add all the necessary code to connect Core Data with our project.


2 Answers

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)!
like image 169
jomafer Avatar answered Oct 05 '22 17:10

jomafer


Swift 5

Step 1. Create Simple app with CoreData option

enter image description here

Step 2. Open .xcdatamodeld file and add Entity, Attributes this way

enter image description here

Step 3. your AppDelegate should have Core Data stack methods

Step 4. Make sure you have swift code snipe as following

import UIKit
import CoreData

class ViewController: UIViewController {

    // MARK: Variables declearations
    let appDelegate = UIApplication.shared.delegate as! AppDelegate //Singlton instance
    var context:NSManagedObjectContext!

    // MARK: View Controller life cycle methods
    override func viewDidLoad() {
        super.viewDidLoad()

        openDatabse()
    }

    // MARK: Methods to Open, Store and Fetch data
    func openDatabse()
    {
        context = appDelegate.persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
        let newUser = NSManagedObject(entity: entity!, insertInto: context)
        saveData(UserDBObj:newUser)
    }

    func saveData(UserDBObj:NSManagedObject)
    {
        UserDBObj.setValue("RDC", forKey: "username")
        UserDBObj.setValue("1234", forKey: "password")
        UserDBObj.setValue("21", forKey: "age")

        print("Storing Data..")
        do {
            try context.save()
        } catch {
            print("Storing data Failed")
        }

        fetchData()
    }

    func fetchData()
    {
        print("Fetching Data..")
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
        request.returnsObjectsAsFaults = false
        do {
            let result = try context.fetch(request)
            for data in result as! [NSManagedObject] {
                let userName = data.value(forKey: "username") as! String
                let age = data.value(forKey: "age") as! String
                print("User Name is : "+userName+" and Age is : "+age)
            }
        } catch {
            print("Fetching data Failed")
        }
    }
}

Step 5. Run on Device and see log for core data results

like image 35
swiftBoy Avatar answered Oct 05 '22 18:10

swiftBoy