Search code examples
core-dataswift3xcode8

How to compute with Core Data


I'm trying to make a small program that keeps count of the amount of times pressed on a button. I'm using Core Data to store the information. The only problem is that I can't figure out how to compute with the information in the core data. If someone can tell me how to make a variable in the code equal to the value of the information in the Core Data I know enough. If there is another way to compute with the Core Data I would like to know about.

import UIKit
import CoreData

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    let context = appDelegate.persistentContainer.viewContext



    /*let newUser = NSEntityDescription.insertNewObject(forEntityName: "Data", into: context)

    newUser.setValue(number, forKey: "number")

    do{
        try context.save()
        print("Saved")
    }catch{
        print("Error occured in the saving process.")
    }*/




    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Data")

    request.returnsObjectsAsFaults = false

    do{
        let results = try context.fetch(request)

        if results.count > 0{
            for result in results as! [NSManagedObject]{

                if let number = result.value(forKey: "number") as? Double{
                    print("number is ", number)
                result.setValue(number + 1, forKey: "number")
                        do{
                            try context.save()
                        }catch{

                }
            }
            }
        }
    }catch{
        print("Error with fetching data.")
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

var number = 0.0

}

The error it's given on the line with nummer = number += 1: Cannot assign value of type '()' to type 'Double'

I appreciate all of your answers.


Solution

  • This has nothing to do with Core Data. This line doesn't make sense:

    nummer = nummerVar += 1
    

    The += operator increases nummerVar in place. You're assigning this to number, but the return value of the += operation is not a Double, so you can't assign it to a Double.

    I'm not completely sure what you intended here. You might have meant

    nummer = nummerVar + 1
    

    Or maybe you meant

    nummerVar += 1
    nummer = nummerVar
    

    Either of those are valid code, but which one you need depends on what you're trying to do.