0

I'm new to Swift and I wrote a AppDelegate function to pre-load Core Data with a test plist. However, whatever I do, when I try to load it in a tableView it returns "nil" objects in the context:

in the AppDelegate:

func importPlistSeedData() {
        let rulesPath = Bundle.main.path(forResource: "rulesTest", ofType: 
"plist")!
        let rulesArray = NSArray(contentsOfFile: rulesPath)!

        for dict in rulesArray {

            let concept = Concept(context: managedContext)

            let conceptDict = dict as! [String: Any]

            concept.number = conceptDict["id"] as! Int16

             concept.title = conceptDict["title"] as? String

             concept.titleTranslationRu = conceptDict["titleTranslationRu"] as? String

             concept.content = conceptDict["content"] as? String

             let imageName = conceptDict["imageName"] as? String
             let image = UIImage(named: imageName!)
             let photoData = UIImagePNGRepresentation(image!)!

            concept.picture1 = NSData(data: photoData) as Data

            concept.completed = conceptDict["completed"] as! Bool

        }

         saveContext()
    }

     func saveContext () {
         guard managedContext.hasChanges else { return }

         do {
            try managedContext.save()
         } catch {
             let nserror = error as NSError
             print("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }



    func importPlistDataIfNeeded() {

         let fetchRequest = NSFetchRequest<Concept>(entityName: "Concept")
         let count = try! managedContext.count(for: fetchRequest)

       guard count == 0 else { return }

            do {
             let results = try managedContext.fetch(fetchRequest)
             results.forEach({ managedContext.delete($0) })

         saveContext()

            importPlistSeedData()
         } catch let error as NSError {
            print("Error fetching: \(error), \(error.userInfo)")
        }
    }

And in the TableView:

import UIKit
import CoreData

class ConceptsTableViewController: UITableViewController {


var fetchRequest: NSFetchRequest<Concept>?
var concepts: [Concept] = []

var managedContext: NSManagedObjectContext!


override func viewDidLoad() {
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation 
 bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem



    guard let model = 
  managedContext.persistentStoreCoordinator?.managedObjectModel, let 
  conceptFetchRequest = model.fetchRequestTemplate(forName: 
  "ConceptFetchRequest") as? NSFetchRequest<Concept> else {return}

    self.fetchRequest = conceptFetchRequest

    fetchAndReload()

}



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source


override func tableView(_ tableView: UITableView, numberOfRowsInSection 
section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return concepts.count
}

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
 IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "conceptsCell", 
 for: indexPath)

    let concept = concepts[indexPath.row]

    cell.textLabel?.text = "\(concept.number)  \(String(describing: 
 concept.title))"
    cell.detailTextLabel?.text = concept.titleTranslationRu

    return cell
    }

}

extension ConceptsTableViewController {
    func fetchAndReload() {

        guard let fetchRequest = fetchRequest else {
            return
        }

        do {
            concepts = try managedContext.fetch(fetchRequest)
            tableView.reloadData()
        } catch let error as NSError {
            print("Could not fetch \(error), \(error.userInfo)")
        }
    }
}
Paulw11
  • 108,386
  • 14
  • 159
  • 186
  • log says: "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" "fetchRequest NSFetchRequest? nil" "concepts [Arabic.Concept] 0 values" "managedContext NSManagedObjectContext! nil" – Roman Potapov Jul 29 '18 at 05:44
  • Please do read about optional and forced unwrapping – user1046037 Jul 29 '18 at 06:12
  • `managedContext` in `ConceptsTableViewController` is not initialized and therefore `nil`. – vadian Jul 29 '18 at 06:49

0 Answers0