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!
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.
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.
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)!
Swift 5
Step 1. Create Simple app with CoreData option
Step 2. Open .xcdatamodeld file and add Entity, Attributes this way
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With