2

My swift code below takes 2 image litterals and then saves then into core data. All I want to is in a func fetch is print in the dubgg area how many attributes are saved into core data. So in the debugg section it should say there are 2 items saved in the debugg section.

import UIKit
import CoreData

class ViewController: UIViewController {


let appDelegate = UIApplication.shared.delegate as! AppDelegate //Singlton instance

lazy var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

var piczy = [UIImage]()

override func viewDidLoad() {
    super.viewDidLoad()

    let newUser = User(context: context)
    let newUser2 = User(context: context)
    newUser.pic = #imageLiteral(resourceName: "Jessica").jpegData(compressionQuality: 0.9) as NSObject?


    newUser2.pic =  #imageLiteral(resourceName: "Jessica").jpegData(compressionQuality: 0.9) as NSObject?



    save()

}
func save() {

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")

    do {

     let jake =   try context.count(for: fetchRequest)

        print(jake)

    } catch let error as NSError {
        print("Could not fetch \(error) ")
    }

}
  • 1
    You are making the same mistake as in one of your previous questions. The second picture overwrites the first. And `fetch()` right before `save()` makes no sense. – vadian Jan 20 '20 at 19:14
  • @vadian I edited my code should fix the saving over part. –  Jan 20 '20 at 21:36
  • Your code crashes because the context is `nil`. Why don't you adopt my suggestion to declare the context lazily and to use a specific fetch request? To determine how many records are saved there is an API: [count(for:)](https://developer.apple.com/documentation/coredata/nsmanagedobjectcontext/1506868-count) – vadian Jan 20 '20 at 21:56
  • @vadian edited my code above. –  Jan 20 '20 at 23:32
  • Please read my comments. Rather than `try context.fetch(fetchRequest)` write `try context.count(for: fetchRequest)` to get the number of saved records. And once again `fetch()` right before `save()` is pointless and your save method doesn't save anything. It's still unclear what you want *exactly* to accomplish. – vadian Jan 21 '20 at 09:53
  • @vadian edited code with your suggestions above getting a runtime error of Thread 1: EXC_BAD_INSTRUCTION at newUser.pic = #imageLiteral(resourceName: "Jessica").jpegData(compressionQuality: 0.9) as NSObject? –  Jan 21 '20 at 23:30

0 Answers0